예제 #1
0
        /// <summary>
        /// checks if the result for this query is already cached.
        /// If not, the result is retrieved from the database.
        /// The result is added to the cache, and the result is returned
        /// as a DataSet from the cache.
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="ATable">can already have some prepared columns; optional parameter, can be null
        /// </param>
        /// <param name="ADataBase">An instantiated <see cref="TDataBase" /> object, or null (default = null). If null
        /// gets passed then the Method executes DB commands with the 'globally available'
        /// <see cref="DBAccess.GDBAccessObj" /> instance, otherwise with the instance that gets passed in with this
        /// Argument!</param>
        /// <returns>void</returns>
        public DataSet GetDataSet(String sql, DataTable ATable, TDataBase ADataBase = null)
        {
            TDataBase      DBAccessObj = DBAccess.GetDBAccessObj(ADataBase);
            TDBTransaction ReadTransaction;
            Boolean        NewTransaction = false;
            DataSet        newDataSet;

            int counter = 0;

            foreach (string sqlstr in storedSQLQuery)
            {
                if (sqlstr == sql)
                {
                    // create a clone of the result, so that the returned datasets
                    // can be treated separately
                    return(((DataSet)storedDataSet[counter]).Copy());
                }

                counter++;
            }

            try
            {
                ReadTransaction = DBAccessObj.GetNewOrExistingTransaction(IsolationLevel.ReadCommitted,
                                                                          TEnforceIsolationLevel.eilMinimum,
                                                                          out NewTransaction);

                if (ATable == null)
                {
                    newDataSet = DBAccessObj.Select(sql, "Cache", ReadTransaction);
                }
                else
                {
                    newDataSet = new DataSet();
                    newDataSet.Tables.Add(ATable);
                    ATable.TableName = "Cache";
                    DBAccessObj.Select(newDataSet, sql, "Cache", ReadTransaction);
                }
            }
            finally
            {
                if (NewTransaction)
                {
                    DBAccessObj.CommitTransaction();
                }
            }
            storedDataSet.Add(newDataSet);
            storedSQLQuery.Add(sql);

            // return a copy, so that changes to the dataset don't affect the stored copy.
            return(newDataSet.Copy());
        }
예제 #2
0
        public static bool GetGiftsForFieldChangeAdjustment(ref GiftBatchTDS AGiftDS, Int32 ALedgerNumber,
                                                            Int64 ARecipientKey,
                                                            DateTime AStartDate,
                                                            DateTime AEndDate,
                                                            Int64 AOldField,
                                                            out TVerificationResultCollection AMessages)
        {
            TDBTransaction Transaction = new TDBTransaction();
            TDataBase      db          = DBAccess.Connect("GetGiftsForFieldChangeAdjustment");
            GiftBatchTDS   MainDS      = new GiftBatchTDS();

            AMessages = new TVerificationResultCollection();

            db.ReadTransaction(
                ref Transaction,
                delegate
            {
                string SqlStmt = TDataBase.ReadSqlFile("Gift.GetGiftsToAdjustField.sql");

                List <OdbcParameter> parameters = new List <OdbcParameter>();
                OdbcParameter param             = new OdbcParameter("LedgerNumber", OdbcType.Int);
                param.Value = ALedgerNumber;
                parameters.Add(param);
                param       = new OdbcParameter("StartDate", OdbcType.Date);
                param.Value = AStartDate;
                parameters.Add(param);
                param       = new OdbcParameter("EndDate", OdbcType.Date);
                param.Value = AEndDate;
                parameters.Add(param);
                param       = new OdbcParameter("RecipientKey", OdbcType.BigInt);
                param.Value = ARecipientKey;
                parameters.Add(param);
                param       = new OdbcParameter("OldField", OdbcType.BigInt);
                param.Value = AOldField;
                parameters.Add(param);

                db.Select(MainDS, SqlStmt, MainDS.AGiftDetail.TableName, Transaction, parameters.ToArray());

                // get additional data
                foreach (GiftBatchTDSAGiftDetailRow Row in MainDS.AGiftDetail.Rows)
                {
                    AGiftBatchAccess.LoadByPrimaryKey(MainDS, Row.LedgerNumber, Row.BatchNumber, Transaction);
                    AGiftRow GiftRow =
                        AGiftAccess.LoadByPrimaryKey(MainDS, Row.LedgerNumber, Row.BatchNumber, Row.GiftTransactionNumber, Transaction);

                    Row.DateEntered = GiftRow.DateEntered;
                    Row.DonorKey    = GiftRow.DonorKey;
                    Row.IchNumber   = 0;
                    Row.DonorName   = PPartnerAccess.LoadByPrimaryKey(Row.DonorKey, Transaction)[0].PartnerShortName;
                }
            });

            AGiftDS = MainDS;

            db.CloseDBConnection();

            return(CheckGiftsNotPreviouslyReversed(AGiftDS, out AMessages));
        }
예제 #3
0
        public void SpeedTestLoadIntoTypedTable()
        {
            TDataBase      db = DBAccess.Connect("test");
            TDBTransaction ReadTransaction = new TDBTransaction();
            DateTime       before          = DateTime.Now;
            DateTime       after           = DateTime.Now;
            GiftBatchTDS   ds = new GiftBatchTDS();

            db.ReadTransaction(
                ref ReadTransaction,
                delegate
            {
                string sql = "SELECT PUB_a_gift_detail.*, false AS AlreadyMatched, PUB_a_gift_batch.a_batch_status_c AS BatchStatus " +
                             "FROM PUB_a_gift_batch, PUB_a_gift_detail " +
                             "WHERE 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";

                before            = DateTime.Now;
                DataTable untyped = db.SelectDT(sql, "test", ReadTransaction);
                after             = DateTime.Now;

                TLogging.Log(String.Format("loading all {0} gift details into an untyped table took {1} milliseconds",
                                           untyped.Rows.Count,
                                           (after.Subtract(before)).TotalMilliseconds));

                GiftBatchTDSAGiftDetailTable typed = new GiftBatchTDSAGiftDetailTable();
                before = DateTime.Now;
                db.SelectDT(typed, sql, ReadTransaction, new OdbcParameter[0], 0, 0);
                after = DateTime.Now;

                TLogging.Log(String.Format("loading all {0} gift details into a typed table took {1} milliseconds",
                                           typed.Rows.Count,
                                           (after.Subtract(before)).TotalMilliseconds));

                AMotivationDetailAccess.LoadAll(ds, ReadTransaction);

                before = DateTime.Now;
                db.Select(ds, sql, ds.AGiftDetail.TableName, ReadTransaction);
                after = DateTime.Now;
            });

            TLogging.Log(String.Format("loading all {0} gift details into a typed dataset took {1} milliseconds",
                                       ds.AGiftDetail.Rows.Count,
                                       (after.Subtract(before)).TotalMilliseconds));

            before = DateTime.Now;
            GiftBatchTDS ds2 = new GiftBatchTDS();

            ds2.Merge(ds.AGiftDetail);
            after = DateTime.Now;

            TLogging.Log(String.Format("merging typed table into other dataset took {0} milliseconds",
                                       (after.Subtract(before)).TotalMilliseconds));
        }
예제 #4
0
        public static bool GetGiftsForTaxDeductiblePctAdjustment(ref GiftBatchTDS AGiftDS,
                                                                 Int64 ARecipientKey,
                                                                 DateTime ADateFrom,
                                                                 decimal ANewPct,
                                                                 out TVerificationResultCollection AMessages)
        {
            TDBTransaction Transaction = new TDBTransaction();
            TDataBase      db          = DBAccess.Connect("GetGiftsForTaxDeductiblePctAdjustment");
            GiftBatchTDS   MainDS      = new GiftBatchTDS();

            AMessages = new TVerificationResultCollection();

            db.ReadTransaction(ref Transaction,
                               delegate
            {
                string Query = "SELECT a_gift_detail.*" +

                               " FROM a_gift_detail, a_gift_batch" +

                               " WHERE a_gift_detail.p_recipient_key_n = " + ARecipientKey +
                               " AND a_gift_detail.a_tax_deductible_pct_n <> " + ANewPct +
                               " AND a_gift_detail.a_modified_detail_l <> true" +
                               " AND a_gift_detail.a_tax_deductible_l = true" +
                               " AND a_gift_batch.a_ledger_number_i = a_gift_detail.a_ledger_number_i" +
                               " AND a_gift_batch.a_batch_number_i = a_gift_detail.a_batch_number_i" +
                               " AND a_gift_batch.a_ledger_number_i = a_gift_detail.a_ledger_number_i" +
                               " AND a_gift_batch.a_batch_status_c = 'Posted' " +
                               " AND a_gift_batch.a_gl_effective_date_d >= '" + ADateFrom.ToString("yyyy-MM-dd") + "'";

                db.Select(MainDS, Query, MainDS.AGiftDetail.TableName, Transaction);

                // get additional data
                foreach (GiftBatchTDSAGiftDetailRow Row in MainDS.AGiftDetail.Rows)
                {
                    AGiftBatchAccess.LoadByPrimaryKey(MainDS, Row.LedgerNumber, Row.BatchNumber, Transaction);
                    AGiftRow GiftRow =
                        AGiftAccess.LoadByPrimaryKey(MainDS, Row.LedgerNumber, Row.BatchNumber, Row.GiftTransactionNumber, Transaction);

                    Row.DateEntered = GiftRow.DateEntered;
                    Row.DonorKey    = GiftRow.DonorKey;
                    Row.DonorName   = PPartnerAccess.LoadByPrimaryKey(Row.DonorKey, Transaction)[0].PartnerShortName;
                }
            });

            AGiftDS = MainDS;

            return(TAdjustmentWebConnector.CheckGiftsNotPreviouslyReversed(AGiftDS, out AMessages));
        }
예제 #5
0
        /// <summary>
        /// return a table with gift details for the given date with donor partner keys and bank account numbers
        /// </summary>
        private static bool GetGiftsByDate(Int32 ALedgerNumber,
                                           BankImportTDS AMainDS,
                                           DateTime ADateEffective,
                                           string ABankAccountCode,
                                           out List <int> AGiftBatchNumbers)
        {
            TDataBase      db          = DBAccess.Connect("GetGiftsByDate");
            TDBTransaction transaction = db.BeginTransaction(IsolationLevel.ReadUncommitted);

            // first get all gifts, even those that have no bank account associated
            string stmt = TDataBase.ReadSqlFile("BankImport.GetDonationsByDate.sql");

            OdbcParameter[] parameters = new OdbcParameter[3];
            parameters[0]       = new OdbcParameter("ALedgerNumber", OdbcType.Int);
            parameters[0].Value = ALedgerNumber;
            parameters[1]       = new OdbcParameter("ADateEffective", OdbcType.Date);
            parameters[1].Value = ADateEffective;
            parameters[2]       = new OdbcParameter("ABankAccountCode", OdbcType.VarChar);
            parameters[2].Value = ABankAccountCode;

            db.SelectDT(AMainDS.AGiftDetail, stmt, transaction, parameters, 0, 0);

            // calculate the totals of gifts
            AMainDS.AGift.Clear();

            AGiftBatchNumbers = new List <int>();

            foreach (BankImportTDSAGiftDetailRow giftdetail in AMainDS.AGiftDetail.Rows)
            {
                BankImportTDSAGiftRow giftRow =
                    (BankImportTDSAGiftRow)AMainDS.AGift.Rows.Find(new object[] { giftdetail.LedgerNumber, giftdetail.BatchNumber,
                                                                                  giftdetail.GiftTransactionNumber });

                if (giftRow == null)
                {
                    giftRow = AMainDS.AGift.NewRowTyped(true);
                    giftRow.LedgerNumber          = giftdetail.LedgerNumber;
                    giftRow.BatchNumber           = giftdetail.BatchNumber;
                    giftRow.GiftTransactionNumber = giftdetail.GiftTransactionNumber;
                    giftRow.TotalAmount           = 0;
                    giftRow.DonorKey = giftdetail.DonorKey;
                    AMainDS.AGift.Rows.Add(giftRow);
                }

                giftRow.TotalAmount += giftdetail.GiftTransactionAmount;

                if (!AGiftBatchNumbers.Contains(giftRow.BatchNumber))
                {
                    AGiftBatchNumbers.Add(giftRow.BatchNumber);
                }
            }

            // get PartnerKey and banking details (most important BankAccountNumber) for all donations on the given date
            stmt                = TDataBase.ReadSqlFile("BankImport.GetBankAccountByDate.sql");
            parameters          = new OdbcParameter[2];
            parameters[0]       = new OdbcParameter("LedgerNumber", OdbcType.Int);
            parameters[0].Value = ALedgerNumber;
            parameters[1]       = new OdbcParameter("ADateEffective", OdbcType.Date);
            parameters[1].Value = ADateEffective;
            // TODO ? parameters[2] = new OdbcParameter("ABankAccountCode", OdbcType.VarChar);
            //parameters[2].Value = ABankAccountCode;

            // There can be several donors with the same banking details
            AMainDS.PBankingDetails.Constraints.Clear();

            db.Select(AMainDS, stmt, AMainDS.PBankingDetails.TableName, transaction, parameters);
            transaction.Rollback();

            return(true);
        }
예제 #6
0
        /// <summary>
        /// checks if the result for this query is already cached.
        /// If not, the result is retrieved from the database.
        /// The result is added to the cache, and the result is returned
        /// as a DataSet from the cache.
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="AParameters">odbc parameters</param>
        /// <param name="ATable">can already have some prepared columns; optional parameter, can be null
        /// </param>
        /// <param name="ADataBase">An instantiated <see cref="TDataBase" /> object, or null (default = null). If null
        /// gets passed then the Method executes DB commands with a new DataBase connection</param>
        /// <returns>void</returns>
        public DataSet GetDataSet(String sql, OdbcParameter[] AParameters, DataTable ATable, TDataBase ADataBase = null)
        {
            TDataBase      DBAccessObj     = DBAccess.Connect("GetDataSet", ADataBase);
            TDBTransaction ReadTransaction = new TDBTransaction();
            Boolean        NewTransaction  = false;
            DataSet        newDataSet;

            int counter = 0;

            foreach (string sqlstr in storedSQLQuery)
            {
                if (sqlstr == sql)
                {
                    bool SameParameters = false;

                    if (AParameters == null && storedParameters[counter] == null)
                    {
                        SameParameters = true;
                    }
                    else if (AParameters == null || storedParameters[counter] == null)
                    {
                        SameParameters = false;
                    }
                    else if (AParameters.Length != ((OdbcParameter[])storedParameters[counter]).Length)
                    {
                        SameParameters = false;
                    }
                    else
                    {
                        int countParam = 0;

                        SameParameters = true;

                        foreach (OdbcParameter p in AParameters)
                        {
                            if (p.OdbcType != ((OdbcParameter[])storedParameters[counter])[countParam].OdbcType)
                            {
                                SameParameters = false;
                            }
                            else
                            {
                                SameParameters = (p.Value.ToString() == ((OdbcParameter[])storedParameters[counter])[countParam].ToString());
                            }
                            countParam++;
                        }
                    }

                    if (SameParameters)
                    {
                        // create a clone of the result, so that the returned datasets
                        // can be treated separately
                        return(((DataSet)storedDataSet[counter]).Copy());
                    }
                }

                counter++;
            }

            try
            {
                ReadTransaction = DBAccessObj.GetNewOrExistingTransaction(IsolationLevel.ReadCommitted,
                                                                          out NewTransaction);

                if (ATable == null)
                {
                    newDataSet = DBAccessObj.Select(sql, "Cache", ReadTransaction, AParameters);
                }
                else
                {
                    newDataSet = new DataSet();
                    newDataSet.Tables.Add(ATable);
                    ATable.TableName = "Cache";
                    DBAccessObj.Select(newDataSet, sql, "Cache", ReadTransaction, AParameters);
                }
            }
            finally
            {
                if (NewTransaction && (ReadTransaction != null))
                {
                    ReadTransaction.Rollback();
                }
            }
            storedDataSet.Add(newDataSet);
            storedSQLQuery.Add(sql);
            storedParameters.Add(AParameters);

            // return a copy, so that changes to the dataset don't affect the stored copy.
            return(newDataSet.Copy());
        }
예제 #7
0
        /// <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'";

            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
예제 #8
0
        /// <summary>
        /// load budgets
        /// </summary>
        /// <param name="ALedgerNumber"></param>
        /// <returns></returns>
        private bool LoadBudgetForConsolidate(Int32 ALedgerNumber)
        {
            FBudgetTDS = new BudgetTDS();

            TDBTransaction Transaction = new TDBTransaction();
            TDataBase      db          = DBAccess.Connect("Budget");

            db.ReadTransaction(
                ref Transaction,
                delegate
            {
                ALedgerAccess.LoadByPrimaryKey(FBudgetTDS, ALedgerNumber, Transaction);

                string sqlLoadBudgetForThisAndNextYear =
                    string.Format("SELECT * FROM PUB_{0} WHERE {1}=? AND ({2} = ? OR {2} = ?)",
                                  ABudgetTable.GetTableDBName(),
                                  ABudgetTable.GetLedgerNumberDBName(),
                                  ABudgetTable.GetYearDBName());

                List <OdbcParameter> parameters = new List <OdbcParameter>();
                OdbcParameter param             = new OdbcParameter("ledgernumber", OdbcType.Int);
                param.Value = ALedgerNumber;
                parameters.Add(param);
                param       = new OdbcParameter("thisyear", OdbcType.Int);
                param.Value = FBudgetTDS.ALedger[0].CurrentFinancialYear;
                parameters.Add(param);
                param       = new OdbcParameter("nextyear", OdbcType.Int);
                param.Value = FBudgetTDS.ALedger[0].CurrentFinancialYear + 1;
                parameters.Add(param);

                db.Select(FBudgetTDS, sqlLoadBudgetForThisAndNextYear, FBudgetTDS.ABudget.TableName, Transaction,
                          parameters.ToArray());

                string sqlLoadBudgetPeriodForThisAndNextYear =
                    string.Format("SELECT {0}.* FROM PUB_{0}, PUB_{1} WHERE {0}.a_budget_sequence_i = {1}.a_budget_sequence_i AND " +
                                  "{2}=? AND ({3} = ? OR {3} = ?)",
                                  ABudgetPeriodTable.GetTableDBName(),
                                  ABudgetTable.GetTableDBName(),
                                  ABudgetTable.GetLedgerNumberDBName(),
                                  ABudgetTable.GetYearDBName());

                db.Select(FBudgetTDS,
                          sqlLoadBudgetPeriodForThisAndNextYear,
                          FBudgetTDS.ABudgetPeriod.TableName,
                          Transaction,
                          parameters.ToArray());

                // Accept row changes here so that the Client gets 'unmodified' rows
                FBudgetTDS.AcceptChanges();

                FGLPostingDS = new GLPostingTDS();
                AAccountAccess.LoadViaALedger(FGLPostingDS, ALedgerNumber, Transaction);
                AAccountHierarchyDetailAccess.LoadViaALedger(FGLPostingDS, ALedgerNumber, Transaction);
                ACostCentreAccess.LoadViaALedger(FGLPostingDS, ALedgerNumber, Transaction);
                ALedgerAccess.LoadByPrimaryKey(FGLPostingDS, ALedgerNumber, Transaction);

                // get the glm sequences for this year and next year
                for (int i = 0; i <= 1; i++)
                {
                    int Year = FGLPostingDS.ALedger[0].CurrentFinancialYear + i;

                    AGeneralLedgerMasterRow TemplateRow = (AGeneralLedgerMasterRow)FGLPostingDS.AGeneralLedgerMaster.NewRowTyped(false);

                    TemplateRow.LedgerNumber = ALedgerNumber;
                    TemplateRow.Year         = Year;

                    FGLPostingDS.AGeneralLedgerMaster.Merge(AGeneralLedgerMasterAccess.LoadUsingTemplate(TemplateRow, Transaction));
                }

                string sqlLoadGLMPeriodForThisAndNextYear =
                    string.Format("SELECT {0}.* FROM PUB_{0}, PUB_{1} WHERE {0}.a_glm_sequence_i = {1}.a_glm_sequence_i AND " +
                                  "{2}=? AND ({3} = ? OR {3} = ?)",
                                  AGeneralLedgerMasterPeriodTable.GetTableDBName(),
                                  AGeneralLedgerMasterTable.GetTableDBName(),
                                  AGeneralLedgerMasterTable.GetLedgerNumberDBName(),
                                  AGeneralLedgerMasterTable.GetYearDBName());

                db.Select(FGLPostingDS,
                          sqlLoadGLMPeriodForThisAndNextYear,
                          FGLPostingDS.AGeneralLedgerMasterPeriod.TableName,
                          Transaction,
                          parameters.ToArray());
            });

            FGLPostingDS.AcceptChanges();

            return(true);
        }
예제 #9
0
        /// <summary>
        /// Creates a list of locations for a given Partner.
        /// </summary>
        /// <remarks>Corresponds in parts with with Progress 4GL Method
        /// 'GetPartnerLocations' in partner/maillib.p.</remarks>
        /// <param name="APartnerKey">PartnerKey of the Partner being processed.</param>
        /// <param name="AMailingAddressesOnly">If true: only include addresses with mailing flag set.</param>
        /// <param name="AIncludeCurrentAddresses">If true: include current addresses.</param>
        /// <param name="AIncludeFutureAddresses">If true: include future addresses.</param>
        /// <param name="AIncludeExpiredAddresses">If true: include expired addresses.</param>
        /// <param name="APartnerLocations">The Locations of the Partner being processed.</param>
        /// <param name="ADataBase">An instantiated <see cref="TDataBase" /> object, or null (default = null). If null
        /// gets passed then the Method executes DB commands with a new Database connection</param>
        /// <returns>False if an invalid PartnerKey was passed in or if Petra Security
        /// denied access to the Partner, otherwise true.</returns>
        public static bool GetPartnerLocations(Int64 APartnerKey,
                                               bool AMailingAddressesOnly,
                                               bool AIncludeCurrentAddresses,
                                               bool AIncludeFutureAddresses,
                                               bool AIncludeExpiredAddresses,
                                               out PPartnerLocationTable APartnerLocations,
                                               TDataBase ADataBase = null)
        {
            TDBTransaction ReadTransaction;
            Boolean        NewTransaction;

            String  SelectSQL;
            DataSet FillDataSet;

            OdbcParameter param;

            // Initialise out Argument
            APartnerLocations = null;

            if (APartnerKey > 0)
            {
                TLogging.LogAtLevel(8, "TMailing.GetPartnerLocations: Checking access to Partner.");

                if (TSecurity.CanAccessPartnerByKey(APartnerKey, false, ADataBase) ==
                    TPartnerAccessLevelEnum.palGranted)
                {
                    TDataBase db = DBAccess.Connect("GetPartnerLocations", ADataBase);

                    ReadTransaction = db.GetNewOrExistingTransaction(
                        IsolationLevel.ReadCommitted,
                        out NewTransaction);

                    // Load Partner Locations, taking passed in restrictions into account.
                    try
                    {
                        SelectSQL =
                            "SELECT *" +
                            "  FROM PUB_" + PPartnerLocationTable.GetTableDBName() +
                            " WHERE " + PPartnerLocationTable.GetPartnerKeyDBName() + " = ?" +
                            "   AND (NOT ? = true OR (? = true AND " + PPartnerLocationTable.GetSendMailDBName() + " = true))" +
                            "   AND ((? = true AND ((" + PPartnerLocationTable.GetDateEffectiveDBName() + " <= ?" +
                            "          OR " + PPartnerLocationTable.GetDateEffectiveDBName() + " IS NULL)" +
                            "     AND (" + PPartnerLocationTable.GetDateGoodUntilDBName() + " >= ?" +
                            "          OR " + PPartnerLocationTable.GetDateGoodUntilDBName() + " IS NULL)))" +
                            "     OR (? = true AND " + PPartnerLocationTable.GetDateEffectiveDBName() + " > ?)" +
                            "     OR (? = true AND " + PPartnerLocationTable.GetDateGoodUntilDBName() + " < ?))";

                        List <OdbcParameter> parameters = new List <OdbcParameter>();
                        param       = new OdbcParameter("PartnerKey", OdbcType.Decimal, 10);
                        param.Value = APartnerKey;
                        parameters.Add(param);
                        param       = new OdbcParameter("MailingAddressOnly1", OdbcType.Bit);
                        param.Value = AMailingAddressesOnly;
                        parameters.Add(param);
                        param       = new OdbcParameter("MailingAddressOnly2", OdbcType.Bit);
                        param.Value = AMailingAddressesOnly;
                        parameters.Add(param);
                        param       = new OdbcParameter("IncludeCurrentAddresses", OdbcType.Bit);
                        param.Value = AIncludeCurrentAddresses;
                        parameters.Add(param);
                        param       = new OdbcParameter("TodaysDate1", OdbcType.Date);
                        param.Value = DateTime.Now;
                        parameters.Add(param);
                        param       = new OdbcParameter("TodaysDate2", OdbcType.Date);
                        param.Value = DateTime.Now;
                        parameters.Add(param);
                        param       = new OdbcParameter("IncludeFutureAddresses", OdbcType.Bit);
                        param.Value = AIncludeFutureAddresses;
                        parameters.Add(param);
                        param       = new OdbcParameter("TodaysDate3", OdbcType.Date);
                        param.Value = DateTime.Now;
                        parameters.Add(param);
                        param       = new OdbcParameter("IncludeExpiredAddresses", OdbcType.Bit);
                        param.Value = AIncludeExpiredAddresses;
                        parameters.Add(param);
                        param       = new OdbcParameter("TodaysDate4", OdbcType.Date);
                        param.Value = DateTime.Now;
                        parameters.Add(param);

                        /*
                         * Our out Argument 'APartnerLocations' is a Typed DataTable, but SelectDT
                         * returns an untyped DataTable, therefore we need to create a Typed DataTable
                         * that contains the data of the returned untyped DataTable!
                         */
                        FillDataSet       = new DataSet();
                        APartnerLocations = new PPartnerLocationTable(PPartnerLocationTable.GetTableDBName());
                        FillDataSet.Tables.Add(APartnerLocations);

                        db.Select(FillDataSet, SelectSQL,
                                  PPartnerLocationTable.GetTableDBName(),
                                  ReadTransaction,
                                  parameters.ToArray());
//                      TLogging.LogAtLevel(7, "TMailing.GetPartnerLocations:  FillDataSet.Tables.Count: " + FillDataSet.Tables.Count.ToString());
                        FillDataSet.Tables.Remove(APartnerLocations);

                        if (APartnerLocations.Rows.Count > 0)
                        {
//                          TLogging.LogAtLevel(7, "TMailing.GetPartnerLocations: Found " + APartnerLocations.Rows.Count.ToString() + " PartnerLocations found for Partner " + APartnerKey.ToString() + ".");
                        }
                        else
                        {
                            /*
                             * /* No Rows returned = no PartnerLocations for Partner.
                             * That shouldn't happen with existing Partners, but if it does (eg. non-existing
                             * PartnerKey passed in) we return an empty Typed DataTable.
                             */
//                          TLogging.LogAtLevel(7, "TMailing.GetPartnerLocations: No PartnerLocations found for Partner " + APartnerKey.ToString() + "!");
                            APartnerLocations = new PPartnerLocationTable();
                        }
                    }
                    finally
                    {
                        if (NewTransaction)
                        {
                            ReadTransaction.Commit();
                            TLogging.LogAtLevel(7, "TMailing.GetPartnerLocations: committed own transaction.");
                        }
                    }

                    return(true);
                }
                else
                {
                    TLogging.LogAtLevel(8, "TMailing.GetPartnerLocations: Access to Partner DENIED!");

                    // Petra Security prevents us from accessing this Partner -> return false;
                    return(false);
                }
            }
            else
            {
                // Invalid PartnerKey -> return false;
                return(false);
            }
        }
예제 #10
0
        public static ExchangeRateTDS LoadDailyExchangeRateData(bool ADeleteAgedExchangeRatesFirst, DateTime AFromDate, DateTime AToDate)
        {
            // If relevant, we do a clean of the data table first, purging 'aged' data
            if (ADeleteAgedExchangeRatesFirst)
            {
                // We clean up the DER table unless there is an app setting in the server configuration
                // If you want to set this as a developer you create a copy of /inc/template/etc/Server-postgresql.config
                //   and rename it to Server-postgresql.config.my.  Then add a new <add> element with this value set to true.
                //   Then (re)start the server using nant or OPDA, which will generate the working copy of this file.
                if (!TAppSettingsManager.GetBoolean("KeepAgedExchangeRates", false))
                {
                    DoDailyExchangeRateClean();
                }
            }

            ExchangeRateTDS WorkingDS = new ExchangeRateTDS();

            WorkingDS.EnforceConstraints = false;
            TDBTransaction Transaction = new TDBTransaction();
            TDataBase      db          = DBAccess.Connect("LoadDailyExchangeRateData");

            db.ReadTransaction(
                ref Transaction,
                delegate
            {
                // Populate the ExchangeRateTDSADailyExchangeRate table
                //-- This is the complete query for the DAILYEXCHANGERATE TABLE
                //-- It returns all rows from the Journal and Gift Batch tables
                //-- PLUS all the rows from the DailyExchangeRate table that are NOT referenced by the Journal and Gift Batch tables.
                string strSQL = "SELECT * FROM ";
                strSQL       += "( ";

                // This returns all the rows in Daily Exchange rate that do NOT match any journal or gift
                strSQL += "SELECT ";
                strSQL += String.Format(
                    "  0 AS {0}, 0 AS {1}, 'DER' AS {2}, ",
                    ExchangeRateTDSADailyExchangeRateTable.GetJournalUsageDBName(),
                    ExchangeRateTDSADailyExchangeRateTable.GetGiftBatchUsageDBName(),
                    ExchangeRateTDSADailyExchangeRateTable.GetTableSourceDBName());
                strSQL += "  der.* ";
                strSQL += "FROM PUB_a_daily_exchange_rate AS der ";
                // By doing a left join and only selecting the NULL rows we get the rows from DER that are NOT used
                strSQL += "LEFT JOIN ";
                strSQL += "( ";
                // This SELECT returns all the used rows (372 rows in the case of SA-DB)
                strSQL += "SELECT ";
                strSQL += "  j.a_batch_number_i AS a_batch_number_i, ";
                strSQL += "  j.a_transaction_currency_c AS a_from_currency_code_c, ";
                strSQL += "  ldg.a_base_currency_c AS a_to_currency_code_c, ";
                strSQL += "  j.a_date_effective_d AS a_date_effective_from_d, ";
                strSQL += "  j.a_exchange_rate_to_base_n AS a_rate_of_exchange_n ";
                strSQL += "FROM PUB_a_journal AS j ";
                strSQL += "JOIN PUB_a_ledger AS ldg ON ";
                strSQL += "  ldg.a_ledger_number_i = j.a_ledger_number_i ";
                strSQL += "WHERE ";
                strSQL += "  j.a_transaction_currency_c <> ldg.a_base_currency_c ";

                strSQL += Environment.NewLine;
                strSQL += "UNION ALL ";
                strSQL += Environment.NewLine;

                strSQL += "SELECT ";
                strSQL += "  j.a_batch_number_i AS a_batch_number_i, ";
                strSQL += "  r.a_revaluation_currency_c AS a_from_currency_code_c, ";
                strSQL += "  ldg.a_base_currency_c AS a_to_currency_code_c, ";
                strSQL += "  j.a_date_effective_d AS a_date_effective_from_d, ";
                strSQL += "  r.a_exchange_rate_to_base_n AS a_rate_of_exchange_n ";
                strSQL += "FROM a_journal AS j ";
                strSQL += "JOIN a_ledger AS ldg ON ";
                strSQL += "  ldg.a_ledger_number_i = j.a_ledger_number_i ";
                strSQL += "JOIN a_revaluation r ON ";
                strSQL +=
                    "  r.a_ledger_number_i = j.a_ledger_number_i AND r.a_batch_number_i=j.a_batch_number_i AND r.a_journal_number_i=j.a_journal_number_i ";

                strSQL += Environment.NewLine;
                strSQL += "UNION ALL ";
                strSQL += Environment.NewLine;

                strSQL += "SELECT ";
                strSQL += "  gb.a_batch_number_i AS a_batch_number_i, ";
                strSQL += "  gb.a_currency_code_c AS a_from_currency_code_c, ";
                strSQL += "  ldg.a_base_currency_c AS a_to_currency_code_c, ";
                strSQL += "  gb.a_gl_effective_date_d AS a_date_effective_from_d, ";
                strSQL += "  gb.a_exchange_rate_to_base_n AS a_rate_of_exchange_n ";
                strSQL += "FROM PUB_a_gift_batch AS gb ";
                strSQL += "JOIN PUB_a_ledger AS ldg ON ";
                strSQL += "  ldg.a_ledger_number_i = gb.a_ledger_number_i ";
                strSQL += "WHERE ";
                strSQL += "  gb.a_currency_code_c <> ldg.a_base_currency_c ";
                strSQL += ") AS j_and_gb ";
                strSQL += "ON ";
                strSQL += "  der.a_from_currency_code_c = j_and_gb.a_from_currency_code_c ";
                strSQL += "  AND der.a_to_currency_code_c = j_and_gb.a_to_currency_code_c ";
                strSQL += "  AND der.a_date_effective_from_d = j_and_gb.a_date_effective_from_d ";
                strSQL += "  AND der.a_rate_of_exchange_n = j_and_gb.a_rate_of_exchange_n ";
                strSQL += "WHERE ";
                strSQL += "  a_batch_number_i IS NULL ";

                strSQL += Environment.NewLine;
                strSQL += "UNION ALL ";
                strSQL += Environment.NewLine;

                // The second half of the UNION returns all the Forex rows from journal and gift
                //  They are aggregated by from/to/date/rate and the time is the min time.
                //  We also get the usage count as well as whether the row originated in the DER table or one of gift or batch
                strSQL += "SELECT ";
                strSQL += String.Format(
                    "  sum(journalUsage) AS {0}, sum(giftBatchUsage) AS {1}, 'GBJ' AS {2}, ",
                    ExchangeRateTDSADailyExchangeRateTable.GetJournalUsageDBName(),
                    ExchangeRateTDSADailyExchangeRateTable.GetGiftBatchUsageDBName(),
                    ExchangeRateTDSADailyExchangeRateTable.GetTableSourceDBName());
                strSQL += "  a_from_currency_code_c, ";
                strSQL += "  a_to_currency_code_c, ";
                strSQL += "  a_rate_of_exchange_n, ";
                strSQL += "  a_date_effective_from_d, ";
                strSQL += "  min(a_time_effective_from_i), ";
                strSQL += "  NULL AS s_date_created_d, ";
                strSQL += "  NULL AS s_created_by_c, ";
                strSQL += "  NULL AS s_date_modified_d, ";
                strSQL += "  NULL AS s_modified_by_c, ";
                strSQL += "  NULL AS s_modification_id_t ";
                strSQL += "FROM ";
                strSQL += "( ";
                // These are all the used rows again (same as part of the query above) but this time we can count the usages from the two tables
                strSQL += "SELECT ";
                strSQL += "  1 AS journalUsage, ";
                strSQL += "  0 AS giftBatchUsage, ";
                strSQL += "  j.a_transaction_currency_c AS a_from_currency_code_c, ";
                strSQL += "  ldg.a_base_currency_c AS a_to_currency_code_c, ";
                strSQL += "  j.a_date_effective_d AS a_date_effective_from_d, ";
                strSQL += "  j.a_exchange_rate_time_i AS a_time_effective_from_i, ";
                strSQL += "  j.a_exchange_rate_to_base_n AS a_rate_of_exchange_n ";
                strSQL += "FROM PUB_a_journal AS j ";
                strSQL += "JOIN PUB_a_ledger AS ldg ON ";
                strSQL += "  ldg.a_ledger_number_i = j.a_ledger_number_i ";
                strSQL += "WHERE ";
                strSQL += "  j.a_transaction_currency_c <> ldg.a_base_currency_c ";

                strSQL += Environment.NewLine;
                strSQL += "UNION ALL ";
                strSQL += Environment.NewLine;

                strSQL += "SELECT ";
                strSQL += "  1 AS journalUsage, ";
                strSQL += "  0 AS giftBatchUsage, ";
                strSQL += "  r.a_revaluation_currency_c AS a_from_currency_code_c, ";
                strSQL += "  ldg.a_base_currency_c AS a_to_currency_code_c, ";
                strSQL += "  j.a_date_effective_d AS a_date_effective_from_d, ";
                strSQL += "  j.a_exchange_rate_time_i AS a_time_effective_from_i, ";
                strSQL += "  r.a_exchange_rate_to_base_n AS a_rate_of_exchange_n ";
                strSQL += "FROM a_journal AS j ";
                strSQL += "JOIN a_ledger AS ldg ON ";
                strSQL += "  ldg.a_ledger_number_i = j.a_ledger_number_i ";
                strSQL += "JOIN a_revaluation r ON ";
                strSQL +=
                    "  r.a_ledger_number_i = j.a_ledger_number_i AND r.a_batch_number_i=j.a_batch_number_i AND r.a_journal_number_i=j.a_journal_number_i ";

                strSQL += Environment.NewLine;
                strSQL += "UNION ALL ";
                strSQL += Environment.NewLine;

                strSQL += "SELECT ";
                strSQL += "  0 AS journalUsage, ";
                strSQL += "  1 AS giftBatchUsage, ";
                strSQL += "  gb.a_currency_code_c AS a_from_currency_code_c, ";
                strSQL += "  ldg.a_base_currency_c AS a_to_currency_code_c, ";
                strSQL += "  gb.a_gl_effective_date_d AS a_date_effective_from_d, ";
                strSQL += "  0 AS a_time_effective_from_i, ";
                strSQL += "  gb.a_exchange_rate_to_base_n AS a_rate_of_exchange_n ";
                strSQL += "FROM PUB_a_gift_batch AS gb ";
                strSQL += "JOIN PUB_a_ledger AS ldg ON ";
                strSQL += "  ldg.a_ledger_number_i = gb.a_ledger_number_i ";
                strSQL += "WHERE ";
                strSQL += "  gb.a_currency_code_c <> ldg.a_base_currency_c ";
                strSQL += ") AS j_and_gb ";

                // GROUP the second half of the query (the UNION of used rates)
                strSQL += "GROUP BY ";
                strSQL += "  a_from_currency_code_c, ";
                strSQL += "  a_to_currency_code_c, ";
                strSQL += "  a_date_effective_from_d, ";
                strSQL += "  a_rate_of_exchange_n ";
                strSQL += ") AS all_rates ";

                strSQL += ((AFromDate < DateTime.MaxValue) && (AToDate < DateTime.MaxValue)) ?
                          String.Format(" WHERE all_rates.{0}>='{1}' AND all_rates.{0}<='{2}'  ",
                                        ADailyExchangeRateTable.GetDateEffectiveFromDBName(),
                                        AFromDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture),
                                        AToDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)) :
                          String.Empty;

                // ORDER of the outermost SELECT
                strSQL += "ORDER BY ";
                strSQL += "  a_to_currency_code_c, ";
                strSQL += "  a_from_currency_code_c, ";
                strSQL += "  a_date_effective_from_d DESC, ";
                strSQL += "  a_time_effective_from_i DESC ";

                db.Select(WorkingDS, strSQL, WorkingDS.ADailyExchangeRate.TableName, Transaction);


                // Now populate the ExchangeRateTDSADailyExchangerateUsage table
                //-- COMPLETE QUERY TO RETURN ADailyExchangeRateUsage
                //-- Query to return the Daily Exchange Rate Usage details
                //--  Only returns rows that are in a foreign currency
                //-- Querying this table by from/to/date/time will return one row per use case
                //-- If the Journal is 0 the batch refers to a gift batch, otherwise it is a GL batch
                strSQL = "SELECT * FROM ( ";

                //-- This part of the query returns the use cases from the Journal table
                strSQL += "SELECT ";
                strSQL += "  j.a_transaction_currency_c AS a_from_currency_code_c, ";
                strSQL += "  ldg.a_base_currency_c AS a_to_currency_code_c, ";
                strSQL += "  j.a_exchange_rate_to_base_n AS a_rate_of_exchange_n, ";
                strSQL += "  j.a_date_effective_d AS a_date_effective_from_d, ";
                strSQL += "  j.a_exchange_rate_time_i AS a_time_effective_from_i, ";
                strSQL += String.Format(
                    "  j.a_ledger_number_i AS {0}, j.a_batch_number_i AS {1}, j.a_journal_number_i AS {2}, b.a_batch_status_c AS {3}, j.a_journal_description_c AS {4}, b.a_batch_year_i AS {5}, b.a_batch_period_i AS {6}, 'J' AS {7} ",
                    ExchangeRateTDSADailyExchangeRateUsageTable.GetLedgerNumberDBName(),
                    ExchangeRateTDSADailyExchangeRateUsageTable.GetBatchNumberDBName(),
                    ExchangeRateTDSADailyExchangeRateUsageTable.GetJournalNumberDBName(),
                    ExchangeRateTDSADailyExchangeRateUsageTable.GetBatchStatusDBName(),
                    ExchangeRateTDSADailyExchangeRateUsageTable.GetDescriptionDBName(),
                    ExchangeRateTDSADailyExchangeRateUsageTable.GetBatchYearDBName(),
                    ExchangeRateTDSADailyExchangeRateUsageTable.GetBatchPeriodDBName(),
                    ExchangeRateTDSADailyExchangeRateUsageTable.GetTableSourceDBName());
                strSQL += "FROM a_journal j ";
                strSQL += "JOIN a_ledger ldg ";
                strSQL += "  ON ldg.a_ledger_number_i = j.a_ledger_number_i ";
                strSQL += "JOIN a_batch b ";
                strSQL += "  ON b.a_batch_number_i = j.a_batch_number_i ";
                strSQL += "  AND b.a_ledger_number_i = j.a_ledger_number_i ";
                strSQL += "WHERE j.a_transaction_currency_c <> ldg.a_base_currency_c ";

                strSQL += Environment.NewLine;
                strSQL += "UNION ";
                strSQL += Environment.NewLine;

                //-- This part of the query returns the revaluation rows
                strSQL += "SELECT ";
                strSQL += "  r.a_revaluation_currency_c as a_from_currency_code_c, ";
                strSQL += "  ldg.a_base_currency_c AS a_to_currency_code_c, ";
                strSQL += "  r.a_exchange_rate_to_base_n AS a_rate_of_exchange_n, ";
                strSQL += "  j.a_date_effective_d AS a_date_effective_from_d, ";
                strSQL += "  j.a_exchange_rate_time_i AS a_time_effective_from_i, ";
                strSQL += String.Format(
                    "  j.a_ledger_number_i AS {0}, j.a_batch_number_i AS {1}, j.a_journal_number_i AS {2}, b.a_batch_status_c AS {3}, j.a_journal_description_c AS {4}, b.a_batch_year_i AS {5}, b.a_batch_period_i AS {6}, 'J' AS {7} ",
                    ExchangeRateTDSADailyExchangeRateUsageTable.GetLedgerNumberDBName(),
                    ExchangeRateTDSADailyExchangeRateUsageTable.GetBatchNumberDBName(),
                    ExchangeRateTDSADailyExchangeRateUsageTable.GetJournalNumberDBName(),
                    ExchangeRateTDSADailyExchangeRateUsageTable.GetBatchStatusDBName(),
                    ExchangeRateTDSADailyExchangeRateUsageTable.GetDescriptionDBName(),
                    ExchangeRateTDSADailyExchangeRateUsageTable.GetBatchYearDBName(),
                    ExchangeRateTDSADailyExchangeRateUsageTable.GetBatchPeriodDBName(),
                    ExchangeRateTDSADailyExchangeRateUsageTable.GetTableSourceDBName());
                strSQL += "FROM a_journal j ";
                strSQL += "JOIN a_ledger ldg ";
                strSQL += "  ON ldg.a_ledger_number_i = j.a_ledger_number_i ";
                strSQL += "JOIN a_batch b ";
                strSQL += "  ON b.a_batch_number_i = j.a_batch_number_i ";
                strSQL += "  AND b.a_ledger_number_i = j.a_ledger_number_i ";
                strSQL += "JOIN a_revaluation r ";
                strSQL +=
                    "  ON r.a_ledger_number_i = j.a_ledger_number_i AND r.a_batch_number_i=j.a_batch_number_i AND r.a_journal_number_i=j.a_journal_number_i ";

                strSQL += Environment.NewLine;
                strSQL += "UNION ";
                strSQL += Environment.NewLine;

                //-- This part of the query returns the use cases from the Gift Batch table
                strSQL += "SELECT ";
                strSQL += "  gb.a_currency_code_c AS a_from_currency_code_c, ";
                strSQL += "  ldg.a_base_currency_c AS a_to_currency_code_c, ";
                strSQL += "  gb.a_exchange_rate_to_base_n AS a_rate_of_exchange_n, ";
                strSQL += "  gb.a_gl_effective_date_d AS a_date_effective_from_d, ";
                strSQL += "  0 AS a_time_effective_from_i, ";
                strSQL += String.Format(
                    "  gb.a_ledger_number_i AS {0}, gb.a_batch_number_i AS {1}, 0 AS {2}, gb.a_batch_status_c AS {3}, gb.a_batch_description_c AS {4}, gb.a_batch_year_i AS {5}, gb.a_batch_period_i AS {6}, 'GB' AS {7} ",
                    ExchangeRateTDSADailyExchangeRateUsageTable.GetLedgerNumberDBName(),
                    ExchangeRateTDSADailyExchangeRateUsageTable.GetBatchNumberDBName(),
                    ExchangeRateTDSADailyExchangeRateUsageTable.GetJournalNumberDBName(),
                    ExchangeRateTDSADailyExchangeRateUsageTable.GetBatchStatusDBName(),
                    ExchangeRateTDSADailyExchangeRateUsageTable.GetDescriptionDBName(),
                    ExchangeRateTDSADailyExchangeRateUsageTable.GetBatchYearDBName(),
                    ExchangeRateTDSADailyExchangeRateUsageTable.GetBatchPeriodDBName(),
                    ExchangeRateTDSADailyExchangeRateUsageTable.GetTableSourceDBName());
                strSQL += "FROM a_gift_batch gb ";
                strSQL += "JOIN a_ledger ldg ";
                strSQL += "  ON ldg.a_ledger_number_i = gb.a_ledger_number_i ";
                strSQL += "WHERE gb.a_currency_code_c <> ldg.a_base_currency_c ";

                strSQL += ") AS usage ";

                strSQL += ((AFromDate < DateTime.MaxValue) && (AToDate < DateTime.MaxValue)) ?
                          String.Format(" WHERE usage.{0}>='{1}' AND usage.{0}<='{2}'  ",
                                        ADailyExchangeRateTable.GetDateEffectiveFromDBName(),
                                        AFromDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture),
                                        AToDate.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)) :
                          String.Empty;

                strSQL += "ORDER BY usage.a_date_effective_from_d DESC, usage.a_time_effective_from_i DESC ";

                db.Select(WorkingDS, strSQL, WorkingDS.ADailyExchangeRateUsage.TableName, Transaction);

                // Now we start a tricky bit to resolve potential primary key conflicts when the constraints are turned on.
                // By combining the Journal and Gift Batch data that is not referenced in the exchange rate table we can easily
                //  have introduced conflicts where more than one rate has been used for a given currency pair and effective date/time.
                // This is because there is no constraint that enforces the batch/journal tables to use a time from the exch rate table.
                // So we have to go through all the rows in our data table and potentially change the time to make it possible to get our primary key.

                // Start by creating a data view on the whole result set.  The ordering is important because we are going to step through the set row by row.
                // Within one group of from/to/date it is essential that the first 'source' is the DER table because we don't change the time on that one -
                //   and of course that must stay the same because the user can modify that one.
                // We need to deal with the following possibilities:
                //   From  To   Date         Time  Source   Rate
                //   EUR   GBP  2014-01-01   1234   DER     2.11
                //   EUR   GBP  2014-01-01   1234   GBJ     2.115
                //   EUR   GBP  2014-01-01   1234   GBJ     2.22
                //   EUR   GBP  2014-01-01   1234   GBJ     3.11
                //
                // In the first row we have an entry from the DER table that is not used anywhere, but a (slightly) different rate is actually used
                //   in a Journal.
                // In the other rows we have 3 different rates - all used somewhere.  We need to adjust the times so they are different.

                DataView dv = new DataView(WorkingDS.ADailyExchangeRate, "",
                                           String.Format("{0}, {1}, {2} DESC, {3} DESC, {4}, {5}",
                                                         ADailyExchangeRateTable.GetFromCurrencyCodeDBName(),
                                                         ADailyExchangeRateTable.GetToCurrencyCodeDBName(),
                                                         ADailyExchangeRateTable.GetDateEffectiveFromDBName(),
                                                         ADailyExchangeRateTable.GetTimeEffectiveFromDBName(),
                                                         ExchangeRateTDSADailyExchangeRateTable.GetTableSourceDBName(),
                                                         ADailyExchangeRateTable.GetRateOfExchangeDBName()), DataViewRowState.CurrentRows);

                for (int i = 0; i < dv.Count - 1; i++)
                {
                    // Get the 'current' row and the 'next' one...
                    ExchangeRateTDSADailyExchangeRateRow drThis = (ExchangeRateTDSADailyExchangeRateRow)dv[i].Row;
                    ExchangeRateTDSADailyExchangeRateRow drNext = (ExchangeRateTDSADailyExchangeRateRow)dv[i + 1].Row;

                    if (!drThis.FromCurrencyCode.Equals(drNext.FromCurrencyCode) ||
                        !drThis.ToCurrencyCode.Equals(drNext.ToCurrencyCode) ||
                        !drThis.DateEffectiveFrom.Equals(drNext.DateEffectiveFrom) ||
                        !drThis.TimeEffectiveFrom.Equals(drNext.TimeEffectiveFrom))
                    {
                        // Something is different so our primary key will be ok for the current row
                        continue;
                    }

                    // We have got two (or more) rows with the same potential primary key and different rates/usages.
                    // We need to work out how many rows ahead also have the same time and adjust them all
                    bool moveForwards = (drThis.TimeEffectiveFrom < 43200);
                    int timeOffset    = 60;         // 1 minute

                    // Start by adjusting our 'next' row we are already working with
                    drNext.BeginEdit();
                    int prevTimeEffectiveFrom = drNext.TimeEffectiveFrom;
                    drNext.TimeEffectiveFrom  = (moveForwards) ? prevTimeEffectiveFrom + timeOffset : prevTimeEffectiveFrom - timeOffset;
                    timeOffset = (moveForwards) ? timeOffset + 60 : timeOffset - 60;
                    drNext.EndEdit();
                    i++;                // we can increment our main loop counter now that we have dealt with our 'next' row.
                    TLogging.LogAtLevel(2, String.Format("Modifying {0} row: From {1}, To {2}, Date {3}, Time {4}, new Time {5}",
                                                         drThis.TableSource, drThis.FromCurrencyCode, drThis.ToCurrencyCode, drThis.DateEffectiveFrom.ToString("yyyy-MM-dd"),
                                                         prevTimeEffectiveFrom, drNext.TimeEffectiveFrom), TLoggingType.ToLogfile);

                    // Modify all the rows in the usage table that refer to the previous time
                    OnModifyEffectiveTime(WorkingDS.ADailyExchangeRateUsage, drNext.FromCurrencyCode, drNext.ToCurrencyCode,
                                          drNext.DateEffectiveFrom,
                                          prevTimeEffectiveFrom, drNext.TimeEffectiveFrom, drNext.RateOfExchange);

                    // Now look ahead even further than the 'next' row and modify those times too, adding 1 more minute to each
                    for (int k = i + 1; k < dv.Count; k++)
                    {
                        ExchangeRateTDSADailyExchangeRateRow drLookAhead = (ExchangeRateTDSADailyExchangeRateRow)dv[k].Row;

                        if (!drThis.FromCurrencyCode.Equals(drLookAhead.FromCurrencyCode) ||
                            !drThis.ToCurrencyCode.Equals(drLookAhead.ToCurrencyCode) ||
                            !drThis.DateEffectiveFrom.Equals(drLookAhead.DateEffectiveFrom) ||
                            !drThis.TimeEffectiveFrom.Equals(drLookAhead.TimeEffectiveFrom))
                        {
                            // No more rows match our potential primary key conflict on the 'current' row.
                            break;
                        }

                        // Do exactly the same to this row as we did to the 'next' row above
                        drLookAhead.BeginEdit();
                        prevTimeEffectiveFrom         = drLookAhead.TimeEffectiveFrom;
                        drLookAhead.TimeEffectiveFrom = (moveForwards) ? prevTimeEffectiveFrom + timeOffset : prevTimeEffectiveFrom - timeOffset;
                        timeOffset = (moveForwards) ? timeOffset + 60 : timeOffset - 60;
                        drLookAhead.EndEdit();
                        i++;
                        TLogging.LogAtLevel(2, String.Format("Modifying additional {0} row: From {1}, To {2}, Date {3}, Time {4}, new Time {5}",
                                                             drThis.TableSource, drThis.FromCurrencyCode, drThis.ToCurrencyCode,
                                                             drThis.DateEffectiveFrom.ToString("yyyy-MM-dd"),
                                                             prevTimeEffectiveFrom, drLookAhead.TimeEffectiveFrom), TLoggingType.ToLogfile);

                        OnModifyEffectiveTime(WorkingDS.ADailyExchangeRateUsage, drLookAhead.FromCurrencyCode, drLookAhead.ToCurrencyCode,
                                              drLookAhead.DateEffectiveFrom, prevTimeEffectiveFrom, drLookAhead.TimeEffectiveFrom, drLookAhead.RateOfExchange);
                    }
                }           // check the next row in the table so that it becomes the 'current' row.

                WorkingDS.EnforceConstraints = true;

                // We only load the following data if we are returning ALL exchange rate data
                if ((AFromDate == DateTime.MaxValue) && (AToDate == DateTime.MaxValue))
                {
                    // Load the Corporate exchange rate table using the usual method
                    ACorporateExchangeRateAccess.LoadAll(WorkingDS, Transaction);
                    // Load the daily exchange rate table as the 'raw' table.  The client needs this for adding new rows to check for constraints.
                    // Note: April 2015.  The MissingSchemaAction was added because SQLite gave a mismatched DataType on a_effective_time_i.
                    //   As a result the GUI tests failed on SQLite - as well as the screen not loading(!)
                    //   There should be no difference with PostgreSQL, which worked fine without the parameter.
                    WorkingDS.ARawDailyExchangeRate.Merge(db.SelectDT("SELECT *, 0 AS Unused FROM PUB_a_daily_exchange_rate",
                                                                      "a_raw_daily_exchange_rate",
                                                                      Transaction), false, MissingSchemaAction.Ignore);

                    strSQL  = "SELECT ";
                    strSQL += "  a_ledger_number_i, ";
                    strSQL += "  a_ledger_status_l, ";
                    strSQL += "  max(a_ledger_name_c) AS a_ledger_name_c, ";
                    strSQL += "  max(a_base_currency_c) AS a_base_currency_c, ";
                    strSQL += "  max(a_intl_currency_c) AS a_intl_currency_c, ";
                    strSQL += "  max(a_current_financial_year_i) AS a_current_financial_year_i, ";
                    strSQL += "  max(a_current_period_i) AS a_current_period_i, ";
                    strSQL += "  max(a_number_of_accounting_periods_i) AS a_number_of_accounting_periods_i, ";
                    strSQL += "  max(a_number_fwd_posting_periods_i) AS a_number_fwd_posting_periods_i, ";
                    strSQL += "  min(CurrentPeriodStartDate) AS CurrentPeriodStartDate, ";
                    strSQL += "  max(CurrentPeriodEndDate) AS CurrentPeriodEndDate, ";
                    strSQL += "  max(ForwardPeriodEndDate) AS ForwardPeriodEndDate ";
                    strSQL += "FROM ";
                    strSQL += "( ";
                    strSQL +=
                        "SELECT ldg.*, pd.a_period_start_date_d AS CurrentPeriodStartDate, pd.a_period_end_date_d AS CurrentPeriodEndDate, NULL AS ForwardPeriodEndDate ";
                    strSQL += "FROM a_ledger ldg ";
                    strSQL += "JOIN a_accounting_period pd ";
                    strSQL += "ON ldg.a_ledger_number_i=pd.a_ledger_number_i and ldg.a_current_period_i=pd.a_accounting_period_number_i ";

                    strSQL += "UNION ";

                    strSQL +=
                        "SELECT ldg.*, pd.a_period_start_date_d AS CurrentPeriodStartDate, NULL AS CurrentPeriodEndDate, pd.a_period_end_date_d AS ForwardPeriodEndDate ";
                    strSQL += "FROM a_ledger ldg ";
                    strSQL += "JOIN a_accounting_period pd ";
                    strSQL +=
                        "ON ldg.a_ledger_number_i=pd.a_ledger_number_i and (ldg.a_current_period_i + a_number_fwd_posting_periods_i)=pd.a_accounting_period_number_i ";
                    strSQL += ") AS all_info ";
                    strSQL += "GROUP BY a_ledger_number_i, a_ledger_status_l ";
                    db.Select(WorkingDS, strSQL, WorkingDS.ALedgerInfo.TableName, Transaction);
                }
            });

            // Accept row changes here so that the Client gets 'unmodified' rows
            WorkingDS.AcceptChanges();

            return(WorkingDS);
        }