Ejemplo n.º 1
0
        public void TestModifyGiftBatch()
        {
            TDataBase      db = DBAccess.Connect("test");
            TDBTransaction t  = db.BeginTransaction(IsolationLevel.Serializable);

            GiftBatchTDS MainDS;

            ALedgerAccess.LoadAll(MainDS, t);

            MainDS.ALedger[0].LastGiftBatchNumber++;

            AGiftBatchRow batch = MainDS.AGiftBatch.NewRowTyped();

            batch.LedgerNumber    = MainDS.ALedger[0].LedgerNumber;
            batch.BatchNumber     = MainDS.ALedger[0].LastGiftBatchNumber;
            batch.BankAccountCode = "6000";
            batch.BatchYear       = 1;
            batch.BatchPeriod     = 1;
            batch.CurrencyCode    = "EUR";
            batch.BankCostCentre  = MainDS.ALedger[0].LedgerNumber.ToString() + "00";
            batch.LastGiftNumber  = 2;
            MainDS.AGiftBatch.Rows.Add(batch);

            AGiftRow gift = MainDS.AGift.NewRowTyped();

            gift.LedgerNumber          = batch.LedgerNumber;
            gift.BatchNumber           = batch.BatchNumber;
            gift.GiftTransactionNumber = 1;
            MainDS.AGift.Rows.Add(gift);

            gift = MainDS.AGift.NewRowTyped();
            gift.LedgerNumber          = batch.LedgerNumber;
            gift.BatchNumber           = batch.BatchNumber;
            gift.GiftTransactionNumber = 2;
            gift.LastDetailNumber      = 1;
            MainDS.AGift.Rows.Add(gift);

            AGiftDetailRow giftdetail = MainDS.AGiftDetail.NewRowTyped();

            giftdetail.LedgerNumber          = gift.LedgerNumber;
            giftdetail.BatchNumber           = gift.BatchNumber;
            giftdetail.GiftTransactionNumber = gift.GiftTransactionNumber;
            giftdetail.DetailNumber          = 1;
            giftdetail.MotivationGroupCode   = "GIFT";
            giftdetail.MotivationDetailCode  = "SUPPORT";
            MainDS.AGiftDetail.Rows.Add(giftdetail);

            MainDS.SubmitChanges(t);
            t.Commit();

            // now delete the first gift, and fix the gift detail of the second gift
            t = db.BeginTransaction(IsolationLevel.Serializable);
            MainDS.AGift.Rows.RemoveAt(0);
            MainDS.AGift[0].GiftTransactionNumber       = 1;
            MainDS.AGiftDetail[0].GiftTransactionNumber = 1;
            MainDS.AGiftBatch[0].LastGiftNumber         = 1;

            MainDS.SubmitChanges(t);
            g.Commit();
        }
Ejemplo n.º 2
0
        public void ForeignCurrencySupplier_ExpectDocumentPostingPayingAndReversingWorking()
        {
            //
            // Arrange
            //
            decimal APAccountBalanceBefore;
            decimal BankAccountBefore;
            decimal RevalAccountBefore;
            TVerificationResultCollection VerificationResult;
            int PaymentNumber;

            List <int> DocumentIDs;
            AAPInfos   APInfos;

            CommonNUnitFunctions.ResetDatabase();
            TPetraServerConnector.Connect();

            TDataBase      db          = DBAccess.Connect("ForeignCurrencySupplier_ExpectDocumentPostingPayingAndReversingWorking");
            TDBTransaction transaction = db.BeginTransaction(IsolationLevel.Serializable);

            // Post and pay a document with a foreign currency supplier
            APInfos = PostAndPayForeignSupplierAPDocument("Test Reverse", out PaymentNumber, out DocumentIDs,
                                                          out APAccountBalanceBefore, out BankAccountBefore, out RevalAccountBefore, db);

            transaction.Commit();
            transaction = db.BeginTransaction(IsolationLevel.Serializable);

            //
            // Act: Immediately "un-pay" and "un-post" this invoice!
            //
            VerificationResult = ReversePayment(PaymentNumber, APInfos.PeriodEndDate, DocumentIDs, APInfos.ApDS, db);
            CommonNUnitFunctions.EnsureNullOrEmptyVerificationResult(VerificationResult);   // Guard Assert

            transaction.Commit();
            transaction = db.BeginTransaction(IsolationLevel.Serializable);

            // Save the current amount on the AP account
            decimal APAccountBalanceAfter = new TGet_GLM_Info(FLedgerNumber,
                                                              APInfos.ApAccountCode, APInfos.CostCentreCode, db).YtdActual;
            decimal BankAccountAfter = new TGet_GLM_Info(FLedgerNumber,
                                                         APInfos.BankAccount, APInfos.CostCentreCode, db).YtdForeign;
            decimal RevalAccountAfter = new TGet_GLM_Info(FLedgerNumber,
                                                          APInfos.ForexGainsLossesAccount, APInfos.CostCentreCode, db).YtdActual;

            //
            // Primary Assert: Reversal OK?
            //
            // Now I can see whether anything is left over by all these
            // various transactions, that should have added up to 0.
            // Check the amount on the AP account
            Assert.AreEqual(APAccountBalanceBefore, APAccountBalanceAfter, "After paying then reversing, the AP account should be as before.");
            Assert.AreEqual(BankAccountBefore, BankAccountAfter, "After paying then reversing, the Bank account should be as before.");
            Assert.AreEqual(
                Math.Round(RevalAccountAfter, 2),
                Math.Round(RevalAccountBefore, 2),
                "After paying then reversing, the Forex Gains/Losses Account account should be as before.");

            transaction.Commit();
        }
Ejemplo n.º 3
0
        public void TestSaveNewPartnerWithExistingLocation()
        {
            TDataBase               db          = DBAccess.Connect("TestSaveNewPartnerWithExistingLocation");
            TDBTransaction          Transaction = db.BeginTransaction(IsolationLevel.Serializable);
            TPartnerEditUIConnector connector   = new TPartnerEditUIConnector(db);

            PartnerEditTDS MainDS = new PartnerEditTDS();

            PPartnerRow PartnerRow = TCreateTestPartnerData.CreateNewFamilyPartner(MainDS, db);

            TCreateTestPartnerData.CreateNewLocation(PartnerRow.PartnerKey, MainDS);

            DataSet ResponseDS = new PartnerEditTDS();
            TVerificationResultCollection VerificationResult;

            TSubmitChangesResult result = connector.SubmitChanges(ref MainDS, ref ResponseDS, out VerificationResult);

            Transaction.Commit();

            CommonNUnitFunctions.EnsureNullOrOnlyNonCriticalVerificationResults(VerificationResult,
                                                                                "There was a critical error when saving:");

            Assert.AreEqual(TSubmitChangesResult.scrOK, result, "saving the first partner with a location");

            Int32 LocationKey = MainDS.PLocation[0].LocationKey;

            MainDS = new PartnerEditTDS();

            Transaction = db.BeginTransaction(IsolationLevel.Serializable);

            PartnerRow = TCreateTestPartnerData.CreateNewFamilyPartner(MainDS, db);

            PPartnerLocationRow PartnerLocationRow = MainDS.PPartnerLocation.NewRowTyped();

            PartnerLocationRow.SiteKey     = DomainManager.GSiteKey;
            PartnerLocationRow.PartnerKey  = PartnerRow.PartnerKey;
            PartnerLocationRow.LocationKey = LocationKey;
            MainDS.PPartnerLocation.Rows.Add(PartnerLocationRow);

            ResponseDS = new PartnerEditTDS();

            result = connector.SubmitChanges(ref MainDS, ref ResponseDS, out VerificationResult);
            Transaction.Commit();

            CommonNUnitFunctions.EnsureNullOrOnlyNonCriticalVerificationResults(VerificationResult,
                                                                                "There was a critical error when saving:");

            TDBTransaction ReadTransaction = new TDBTransaction();

            db.ReadTransaction(
                ref ReadTransaction,
                delegate
            {
                PPartnerTable PartnerAtAddress = PPartnerAccess.LoadViaPLocation(
                    DomainManager.GSiteKey, LocationKey, ReadTransaction);
                Assert.AreEqual(2, PartnerAtAddress.Rows.Count, "there should be two partners at this location");
            });
        }
Ejemplo n.º 4
0
        public void SimpleDocument_ExpectPostingAndPayingWorking()
        {
            //
            // Arrange
            //
            decimal Amount = 399.0m;
            decimal APAccountBalanceBefore;
            decimal ABankAccountBefore;
            decimal AExpAccountBefore;
            TVerificationResultCollection VerificationResult;

            List <int> DocumentIDs;
            int        PaymentNumber;
            AAPInfos   APInfos;

            CommonNUnitFunctions.ResetDatabase();
            TPetraServerConnector.Connect();

            TDataBase      db          = DBAccess.Connect("SimpleDocument_ExpectPostingAndPayingWorking");
            TDBTransaction transaction = db.BeginTransaction(IsolationLevel.Serializable);

            APInfos = PostSimpleAPDocument(Amount, "Test", "Detail Item", out APAccountBalanceBefore, out ABankAccountBefore,
                                           out AExpAccountBefore, out DocumentIDs, db);

            transaction.Commit();
            transaction = db.BeginTransaction(IsolationLevel.Serializable);

            //
            // Act: Pay the AP document
            //
            VerificationResult = PayAPDocument(APInfos.ApDS.AApDocument[0].ApDocumentId, Amount,
                                               APInfos.BankAccount, APInfos.CurrencyCode, APInfos.PeriodEndDate, out PaymentNumber, null, db);
            CommonNUnitFunctions.EnsureNullOrEmptyVerificationResult(VerificationResult);   // Guard Assert

            transaction.Commit();

            // Save the current amount on the AP account
            decimal APAccountBalanceAfter = new TGet_GLM_Info(FLedgerNumber,
                                                              APInfos.ApAccountCode, APInfos.CostCentreCode, db).YtdActual;
            decimal BankAccountAfter = new TGet_GLM_Info(FLedgerNumber,
                                                         APInfos.BankAccount, APInfos.CostCentreCode, db).YtdActual;

            //
            // Primary Assert: Paying OK?
            //
            // Check the amount on the AP account
            Assert.AreEqual(0.0m, APAccountBalanceAfter - APAccountBalanceBefore, "after paying the invoice, the AP account should be cleared");
            Assert.AreEqual((-1.0m) * Amount, BankAccountAfter - ABankAccountBefore, "after paying the invoice, the bank account should be credited");
        }
Ejemplo n.º 5
0
        public void TestSaveNewPartnerWithLocation()
        {
            TDataBase               db          = DBAccess.Connect("TestSaveNewPartnerWithLocation");
            TDBTransaction          Transaction = db.BeginTransaction(IsolationLevel.Serializable);
            TPartnerEditUIConnector connector   = new TPartnerEditUIConnector(db);

            PartnerEditTDS MainDS = new PartnerEditTDS();

            PPartnerRow PartnerRow = TCreateTestPartnerData.CreateNewFamilyPartner(MainDS, db);

            TCreateTestPartnerData.CreateNewLocation(PartnerRow.PartnerKey, MainDS);

            DataSet ResponseDS = new PartnerEditTDS();
            TVerificationResultCollection VerificationResult;

            TSubmitChangesResult result = connector.SubmitChanges(ref MainDS, ref ResponseDS, out VerificationResult);

            Transaction.Commit();

            CommonNUnitFunctions.EnsureNullOrOnlyNonCriticalVerificationResults(VerificationResult,
                                                                                "There was a critical error when saving:");

            Assert.AreEqual(TSubmitChangesResult.scrOK, result, "TPartnerEditUIConnector SubmitChanges return value");

            // check the location key for this partner. should not be negative
            Assert.AreEqual(1, MainDS.PPartnerLocation.Rows.Count, "TPartnerEditUIConnector SubmitChanges returns one location");
            Assert.Greater(MainDS.PPartnerLocation[0].LocationKey, 0, "TPartnerEditUIConnector SubmitChanges returns valid location key");
        }
Ejemplo n.º 6
0
        public static Boolean GetConferenceApplications(ref ConferenceApplicationTDS AMainDS, Int64 AConferenceKey)
        {
            // make sure outreach codes are up to date in case it has changed in Unit record
            TAttendeeManagement.RefreshOutreachCode(AConferenceKey);

            TDataBase      db = DBAccess.Connect("GetConferenceApplications");
            TDBTransaction ReadTransaction = db.BeginTransaction(IsolationLevel.ReadCommitted);

            PcConferenceTable ConferenceTable = PcConferenceAccess.LoadByPrimaryKey(AConferenceKey, ReadTransaction);

            if (ConferenceTable.Count == 0)
            {
                ReadTransaction.Rollback();
                throw new Exception("Cannot find conference " + AConferenceKey.ToString("0000000000"));
            }

            string OutreachPrefix = ConferenceTable[0].OutreachPrefix;

            // load application data for all conference attendees from db
            TApplicationManagement.GetApplications(ref AMainDS, AConferenceKey, OutreachPrefix, "all", -1, true, null, false);

            // obtain PPartner records for all the home offices
            foreach (PcAttendeeRow AttendeeRow in AMainDS.PcAttendee.Rows)
            {
                if (AMainDS.PPartner.Rows.Find(new object[] { AttendeeRow.HomeOfficeKey }) == null)
                {
                    PPartnerAccess.LoadByPrimaryKey(AMainDS, AttendeeRow.HomeOfficeKey, ReadTransaction);
                }
            }

            ReadTransaction.Rollback();

            return(true);
        }
Ejemplo n.º 7
0
        public void TestDBAccess_SimpleAutoDBConnAndReadTransactionSelector_JoinExistingTransaction()
        {
            TDataBase      db = DBAccess.Connect("Test");
            TDBTransaction FirstTransaction = db.BeginTransaction(ATransactionName: "FirstTransaction");
            TDBTransaction ReadTransaction  = new TDBTransaction();
            int            Result           = 0;

            DBAccess.SimpleAutoDBConnAndReadTransactionSelector(ATransaction: out ReadTransaction, AName: "SecondTransaction",
                                                                AEncapsulatedDBAccessCode: delegate
            {
                Result =
                    Convert.ToInt32(ReadTransaction.DataBaseObj.ExecuteScalar("SELECT COUNT(*) FROM p_partner WHERE p_partner_key_n = 43005001",
                                                                              ReadTransaction));

                // Is this the expected connection?
                Assert.AreEqual("Default NUnit TTestCommonDB DB Connection", ReadTransaction.DataBaseObj.ConnectionName);
            });

            // Did we get the expected transaction?
            Assert.AreEqual("FirstTransaction", ReadTransaction.TransactionName);

            // Check we get a result
            Assert.AreEqual(1, Result);

            // Check the existing transaction we joined is not rolled back
            Assert.True(ReadTransaction.Valid);

            // Clear up the FirstTransaction we Began earlier
            ReadTransaction.Rollback();
        }
Ejemplo n.º 8
0
        public void TestDBAccess_SimpleAutoDBConnAndReadTransactionSelector_RequestedConnectionJoin()
        {
            if (FDBType == TDBType.SQLite)
            {
                // do not run this test with SQLite
                return;
            }

            TDataBase      RequestedConnection = DBAccess.Connect("New DB Connection");
            TDBTransaction FirstTransaction    = RequestedConnection.BeginTransaction(IsolationLevel.ReadCommitted, -1, "FirstTransaction");
            bool           newTransaction;

            TDBTransaction ReadTransaction = RequestedConnection.GetNewOrExistingTransaction(
                IsolationLevel.ReadCommitted,
                out newTransaction,
                "NewTransaction");

            Assert.AreEqual("New DB Connection", ReadTransaction.DataBaseObj.ConnectionName);

            // Did we get not a new transaction
            Assert.AreEqual(false, newTransaction);

            // Did we get the expected transaction?
            Assert.AreEqual("FirstTransaction", ReadTransaction.TransactionName);

            // Check the transaction we joined is left open
            Assert.True(ReadTransaction.Valid);

            ReadTransaction.Rollback();
            RequestedConnection.CloseDBConnection();
        }
Ejemplo n.º 9
0
        /// create new AP info
        public static AApDocumentRow CreateNewAPInfo(Int64 APartnerKey, ref AccountsPayableTDS AMainDS, TDataBase ADataBase = null)
        {
            TDataBase      db          = DBAccess.Connect("CreateNewAPInfo", ADataBase);
            TDBTransaction Transaction = db.BeginTransaction(IsolationLevel.Serializable);

            ALedgerTable LedgerTable = ALedgerAccess.LoadAll(Transaction);

            AMainDS = TAPTransactionWebConnector.CreateAApDocument(((ALedgerRow)LedgerTable.Rows[0]).LedgerNumber, APartnerKey, true, db);

            // Create a new RecurringGiftBatch
            AApDocumentRow Document = AMainDS.AApDocument[0];

            Document.DocumentCode     = "TEST";
            Document.CreditNoteFlag   = false;
            Document.DateIssued       = DateTime.Today;
            Document.DateEntered      = DateTime.Today;
            Document.TotalAmount      = 0;
            Document.CurrencyCode     = "EUR";
            Document.LastDetailNumber = 0;

            // Create a new RecurringGift record
            AApSupplierRow ApSupplierRow = AMainDS.AApSupplier.NewRowTyped();

            ApSupplierRow.PartnerKey   = APartnerKey;
            ApSupplierRow.CurrencyCode = "EUR";
            AMainDS.AApSupplier.Rows.Add(ApSupplierRow);

            Transaction.Commit();

            return(Document);
        }
Ejemplo n.º 10
0
        /// create a new church
        public static PPartnerRow CreateNewChurchPartner(PartnerEditTDS AMainDS, TDataBase ADataBase = null)
        {
            PPartnerRow    PartnerRow  = CreateNewPartner(AMainDS, ADataBase);
            TDataBase      db          = DBAccess.Connect("CreateNewChurchPartner", ADataBase);
            TDBTransaction Transaction = db.BeginTransaction(IsolationLevel.Serializable);

            // make sure denomination "UNKNOWN" exists as this is the default value
            if (!PDenominationAccess.Exists("UNKNOWN", Transaction))
            {
                PDenominationTable DenominationTable = new PDenominationTable();
                PDenominationRow   DenominationRow   = DenominationTable.NewRowTyped();
                DenominationRow.DenominationCode = "UNKNOWN";
                DenominationRow.DenominationName = "Unknown";
                DenominationTable.Rows.Add(DenominationRow);
                PDenominationAccess.SubmitChanges(DenominationTable, Transaction);
                Transaction.Commit();
            }
            else
            {
                Transaction.Rollback();
            }

            PartnerRow.PartnerClass     = MPartnerConstants.PARTNERCLASS_CHURCH;
            PartnerRow.PartnerShortName = PartnerRow.PartnerKey.ToString() + ", TestChurch";

            PChurchRow ChurchRow = AMainDS.PChurch.NewRowTyped();

            ChurchRow.PartnerKey       = PartnerRow.PartnerKey;
            ChurchRow.ChurchName       = "TestChurch";
            ChurchRow.DenominationCode = "UNKNOWN";
            AMainDS.PChurch.Rows.Add(ChurchRow);

            return(PartnerRow);
        }
Ejemplo n.º 11
0
        private static void CreateOptionTypes()
        {
            TDataBase      db          = DBAccess.Connect("CreateOptionTypes");
            TDBTransaction Transaction = db.BeginTransaction(IsolationLevel.Serializable);

            bool RowsToAdd = false;

            string[, ] OptionTypes = new string[, ]
            {
                {
                    "ADD_ACCOMM_COST_FOR_TOTAL", "Add accommodation costs to get total costs"
                },
                {
                    "COST_PER_DAY", "Calculate conference cost per day"
                },
                {
                    "COST_PER_NIGHT", "Calculate conference cost per night"
                }
            };

            try
            {
                PcConferenceOptionTypeTable OptionTypeTable = PcConferenceOptionTypeAccess.LoadAll(Transaction);

                for (int i = 0; i < 3; i++)
                {
                    if (OptionTypeTable.Rows.Find(new object[] { OptionTypes[i, 0] }) == null)
                    {
                        PcConferenceOptionTypeRow NewRow = OptionTypeTable.NewRowTyped(false);
                        NewRow.OptionTypeCode        = OptionTypes[i, 0];
                        NewRow.OptionTypeDescription = OptionTypes[i, 1];
                        NewRow.UnassignableFlag      = false;
                        NewRow.DeletableFlag         = false;

                        OptionTypeTable.Rows.Add(NewRow);

                        RowsToAdd = true;
                    }
                }

                if (RowsToAdd)
                {
                    // add any new rows to database
                    PcConferenceOptionTypeAccess.SubmitChanges(OptionTypeTable, Transaction);
                }

                Transaction.Commit();
                TLogging.LogAtLevel(7, "TConferenceDataReaderWebConnector.CreateOptionTypes: commit own transaction.");
            }
            catch (Exception Exc)
            {
                TLogging.Log("An Exception occured during the creation of option types:" + Environment.NewLine + Exc.ToString());

                Transaction.Rollback();

                throw;
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// todoComment
        /// </summary>
        /// <param name="AErrorCode"></param>
        /// <param name="AContext"></param>
        /// <param name="AMessageLine1"></param>
        /// <param name="AMessageLine2"></param>
        /// <param name="AMessageLine3"></param>
        /// <param name="AUserID"></param>
        /// <param name="AProcessID"></param>
        public void AddErrorLogEntry(String AErrorCode,
                                     String AContext,
                                     String AMessageLine1,
                                     String AMessageLine2,
                                     String AMessageLine3,
                                     String AUserID,
                                     Int32 AProcessID)
        {
            SErrorLogTable ErrorLogTable;
            SErrorLogRow   NewErrorLogRow;
            DateTime       ErrorLogDateTime;
            String         Context;

            ErrorLogTable    = new SErrorLogTable();
            NewErrorLogRow   = ErrorLogTable.NewRowTyped(false);
            ErrorLogDateTime = DateTime.Now;

            if (AContext != "")
            {
                Context = AContext;
            }
            else
            {
                Context = UNKNOWN_CONTEXT;
            }

            // Set DataRow values
            NewErrorLogRow.ErrorCode     = AErrorCode;
            NewErrorLogRow.UserId        = AUserID.ToUpper();
            NewErrorLogRow.Date          = ErrorLogDateTime;
            NewErrorLogRow.Time          = Conversions.DateTimeToInt32Time(ErrorLogDateTime);
            NewErrorLogRow.ReleaseNumber = TSrvSetting.ApplicationVersion.ToString();
            NewErrorLogRow.FileName      = Context;
            NewErrorLogRow.ProcessId     = AProcessID.ToString();
            NewErrorLogRow.MessageLine1  = AMessageLine1;
            NewErrorLogRow.MessageLine2  = AMessageLine2;
            NewErrorLogRow.MessageLine3  = AMessageLine3;
            ErrorLogTable.Rows.Add(NewErrorLogRow);

            TDataBase      db = DBAccess.Connect("AddErrorLogEntry");
            TDBTransaction WriteTransaction = db.BeginTransaction(IsolationLevel.Serializable);

            // Save DataRow
            try
            {
                SErrorLogAccess.SubmitChanges(ErrorLogTable, WriteTransaction);

                WriteTransaction.Commit();
            }
            catch (Exception Exc)
            {
                TLogging.Log("An Exception occured during the saving of the Error Log:" + Environment.NewLine + Exc.ToString());

                WriteTransaction.Rollback();

                throw;
            }
        }
Ejemplo n.º 13
0
        public void TestLoadGLBatchDataArgumentValidation()
        {
            TVerificationResultCollection VerificationResult = null;
            TDataBase      db          = DBAccess.Connect("TestLoadGLBatchDataArgumentValidation");
            TDBTransaction Transaction = db.BeginTransaction(IsolationLevel.ReadCommitted);

            // Load GL Batch with ledger number less than 1
            string Message = "Validation failed for LoadGLBatchData with ledger number less than 1.";

            try
            {
                TGLPosting.LoadGLBatchData(-1, 1, ref Transaction, ref VerificationResult);
                Assert.Fail(Message);
            }
            catch (EFinanceSystemInvalidLedgerNumberException e)
            {
                Assert.AreEqual(-1, e.LedgerNumber, Message);
            }
            catch
            {
                Assert.Fail(Message);
            }

            // Load GL Batch with batch number less than 1
            Message = "Validation failed for LoadGLBatchData with batch number less than 1.";
            try
            {
                TGLPosting.LoadGLBatchData(43, -1, ref Transaction, ref VerificationResult);
                Assert.Fail(Message);
            }
            catch (EFinanceSystemInvalidBatchNumberException e)
            {
                Assert.AreEqual(43, e.LedgerNumber, Message);
                Assert.AreEqual(-1, e.BatchNumber, Message);
            }
            catch
            {
                Assert.Fail(Message);
            }

            // Load GL Batch with null VerificationResult
            Message            = "Validation failed for LoadGLBatchData with null VerificationResult.";
            VerificationResult = null;
            try
            {
                TGLPosting.LoadGLBatchData(1, 1, ref Transaction, ref VerificationResult);
                Assert.Fail(Message);
            }
            catch (ArgumentException e)
            {
                Assert.AreEqual("Function:Load GL Batch Data - Verifications collection must not be NULL!", e.Message,
                                Message);
            }
            catch
            {
                Assert.Fail(Message);
            }
        }
Ejemplo n.º 14
0
        /// create new PM data
        public static PDataLabelTable CreateNewPMData(long AFromPartnerKey, long AToPartnerKey, IndividualDataTDS AMainDS, TDataBase ADataBase = null)
        {
            TDataBase      db          = DBAccess.Connect("CreateNewPMData", ADataBase);
            TDBTransaction Transaction = db.BeginTransaction(IsolationLevel.ReadCommitted);

            // Create a new DataLabel record
            PDataLabelTable AllDataLabelTable = PDataLabelAccess.LoadAll(Transaction);
            PDataLabelTable DataLabelTable    = new PDataLabelTable();
            PDataLabelRow   DataLabelRow      = DataLabelTable.NewRowTyped();

            // Get the first available key, which is our unique primary key field
            Int32 Key = 1;

            while (AllDataLabelTable.Rows.Find(new object[] { Key }) != null)
            {
                Key++;
            }

            DataLabelRow.Key      = Key;
            DataLabelRow.DataType = "char";
            DataLabelTable.Rows.Add(DataLabelRow);

            // Create a new DataLabelValuePartner record
            PDataLabelValuePartnerRow DataLabelValuePartner = AMainDS.PDataLabelValuePartner.NewRowTyped();

            DataLabelValuePartner.PartnerKey   = AFromPartnerKey;
            DataLabelValuePartner.DataLabelKey = DataLabelRow.Key;
            AMainDS.PDataLabelValuePartner.Rows.Add(DataLabelValuePartner);

            // Create a new PassportDetails record
            IndividualDataTDSPmPassportDetailsRow PassportDetails = AMainDS.PmPassportDetails.NewRowTyped();

            PassportDetails.PartnerKey              = AFromPartnerKey;
            PassportDetails.PassportNumber          = "0";
            PassportDetails.PassportNationalityName = "IRELAND";
            AMainDS.PmPassportDetails.Rows.Add(PassportDetails);

            // Create two new PersonalData records
            PmPersonalDataRow FromPersonalData = AMainDS.PmPersonalData.NewRowTyped();

            FromPersonalData.PartnerKey = AFromPartnerKey;
            FromPersonalData.HeightCm   = 175;
            FromPersonalData.WeightKg   = 80;
            AMainDS.PmPersonalData.Rows.Add(FromPersonalData);

            PmPersonalDataRow ToPersonalData = AMainDS.PmPersonalData.NewRowTyped();

            ToPersonalData.PartnerKey = AToPartnerKey;
            ToPersonalData.WeightKg   = 95;
            AMainDS.PmPersonalData.Rows.Add(ToPersonalData);

            Transaction.Rollback();

            return(DataLabelTable);
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Passes data as a Typed DataSet to the Supplier Edit Screen
        /// </summary>
        public AccountsPayableTDS GetData(Int64 APartnerKey)
        {
            TDBTransaction ReadTransaction;

            // create the DataSet that will later be passed to the Client
            AccountsPayableTDS MainDS = new AccountsPayableTDS();

            ReadTransaction = FDataBase.BeginTransaction(IsolationLevel.RepeatableRead, 5);

            try
            {
                try
                {
                    // Supplier
                    AApSupplierAccess.LoadByPrimaryKey(MainDS, APartnerKey, ReadTransaction);

                    if (MainDS.AApSupplier.Rows.Count == 0)
                    {
                        // Supplier does not exist
                        throw new Exception("supplier does not exist");
                    }
                }
                catch (Exception Exp)
                {
                    ReadTransaction.Rollback();
                    ReadTransaction = new TDBTransaction();
                    TLogging.Log("TSupplierEditUIConnector.LoadData exception: " + Exp.ToString(), TLoggingType.ToLogfile);
                    TLogging.Log(Exp.StackTrace, TLoggingType.ToLogfile);
                    throw;
                }
            }
            finally
            {
                if (ReadTransaction != null)
                {
                    ReadTransaction.Commit();
                }
            }

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

            // Remove all Tables that were not filled with data before remoting them.
            MainDS.RemoveEmptyTables();

            return(MainDS);
        }
Ejemplo n.º 16
0
        public static bool ExportAllTables(out string ADataYmlGzBase64)
        {
            TDataBase      DBConnectionObj = null;
            TDBTransaction ReadTransaction = new TDBTransaction();
            XmlDocument    OpenPetraData   = TYml2Xml.CreateXmlDocument();
            XmlNode        rootNode        = OpenPetraData.FirstChild.NextSibling;

            Assembly TypedTablesAssembly = Assembly.LoadFrom(
                TAppSettingsManager.ApplicationDirectory + Path.DirectorySeparatorChar + "Ict.Petra.Shared.lib.data.dll");

            try
            {
                // Open a separate DB Connection for the exporting of the data...
                DBConnectionObj = DBAccess.Connect("ExportAllTables");

                // ...and start a DB Transaction on that separate DB Connection
                ReadTransaction = DBConnectionObj.BeginTransaction(IsolationLevel.Serializable, 0, "ExportAllTables");

                ExportTables(rootNode, "MSysMan", "", TypedTablesAssembly, ReadTransaction);
                ExportTables(rootNode, "MCommon", "", TypedTablesAssembly, ReadTransaction);
                ExportTables(rootNode, "MPartner", "Partner", TypedTablesAssembly, ReadTransaction);
                ExportTables(rootNode, "MPartner", "Mailroom", TypedTablesAssembly, ReadTransaction);
                ExportTables(rootNode, "MFinance", "Account", TypedTablesAssembly, ReadTransaction);
                ExportTables(rootNode, "MFinance", "Gift", TypedTablesAssembly, ReadTransaction);
                ExportTables(rootNode, "MFinance", "AP", TypedTablesAssembly, ReadTransaction);
                ExportTables(rootNode, "MFinance", "AR", TypedTablesAssembly, ReadTransaction);
                ExportTables(rootNode, "MPersonnel", "Personnel", TypedTablesAssembly, ReadTransaction);
                ExportTables(rootNode, "MPersonnel", "Units", TypedTablesAssembly, ReadTransaction);
                ExportTables(rootNode, "MConference", "", TypedTablesAssembly, ReadTransaction);
                ExportTables(rootNode, "MHospitality", "", TypedTablesAssembly, ReadTransaction);

                ExportSequences(rootNode, ReadTransaction);
            }
            finally
            {
                if (DBConnectionObj != null)
                {
                    ReadTransaction.Rollback();

                    DBConnectionObj.CloseDBConnection();
                }
            }

            ADataYmlGzBase64 = TYml2Xml.Xml2YmlGz(OpenPetraData);

            return(true);
        }
Ejemplo n.º 17
0
        public void TestDBAccess_SimpleAutoDBConnAndReadTransactionSelector_CantJoinExistingTransaction()
        {
            if (FDBType == TDBType.SQLite)
            {
                // do not run this test with SQLite
                return;
            }

            TDataBase      db = DBAccess.Connect("TestDBAccess_SimpleAutoDBConnAndReadTransactionSelector_CantJoinExistingTransaction");
            TDBTransaction FirstTransaction = db.BeginTransaction(ATransactionName: "FirstTransaction");
            TDBTransaction ReadTransaction  = new TDBTransaction();
            int            Result           = 0;

            // Initialize TSrvSetting; needed by DBAccess.Connect()
            var oink = new TSrvSetting();

            Assert.NotNull(oink);

            DBAccess.SimpleAutoDBConnAndReadTransactionSelector(ATransaction: out ReadTransaction, AName: "SecondTransaction",
                                                                AIsolationLevel: IsolationLevel.Serializable,
                                                                AEncapsulatedDBAccessCode: delegate
            {
                Result =
                    Convert.ToInt32(ReadTransaction.DataBaseObj.ExecuteScalar("SELECT COUNT(*) FROM p_partner WHERE p_partner_key_n = 43005001",
                                                                              ReadTransaction));

                // Is this the expected connection?
                Assert.AreEqual("SecondTransaction", ReadTransaction.DataBaseObj.ConnectionName);
            });

            // Did we get the expected transaction?
            Assert.AreEqual("SecondTransaction", ReadTransaction.TransactionName);

            // Check we get a result
            Assert.AreEqual(1, Result);

            // Check the new transaction is rolled back
            Assert.False(ReadTransaction.Valid);

            // Check the existing transaction is not rolled back
            Assert.True(FirstTransaction.Valid);

            // Clear up the FirstTransaction we Began earlier
            FirstTransaction.Rollback();
        }
Ejemplo n.º 18
0
        public void TestPrepareGLBatchForPostingArgumentValidation()
        {
            TVerificationResultCollection VerificationResult = new TVerificationResultCollection();
            TDataBase      db          = DBAccess.Connect("TestPrepareGLBatchForPostingArgumentValidation");
            TDBTransaction Transaction = db.BeginTransaction(IsolationLevel.ReadCommitted);
            GLBatchTDS     MainDS      = null;
            int            BatchPeriod = -1;

            string Message = "Validation failed for PrepareGLBatchForPosting with ledger number less than 1.";

            // Prepare GL Batch For Posting with ledger number less than 1
            try
            {
                TGLPosting.PrepareGLBatchForPosting(out MainDS, -1, 1, ref Transaction, out VerificationResult, null, ref BatchPeriod);
                Assert.Fail(Message);
            }
            catch (EFinanceSystemInvalidLedgerNumberException e)
            {
                Assert.AreEqual(-1, e.LedgerNumber, Message);
            }
            catch
            {
                Assert.Fail(Message);
            }

            // Prepare GL Batch For Posting with batch number less than 1
            Message = "Validation failed for PrepareGLBatchForPosting with batch number less than 1.";
            try
            {
                TGLPosting.PrepareGLBatchForPosting(out MainDS, 43, -1, ref Transaction, out VerificationResult, null, ref BatchPeriod);
                Assert.Fail(Message);
            }
            catch (EFinanceSystemInvalidBatchNumberException e)
            {
                Assert.AreEqual(43, e.LedgerNumber, Message);
                Assert.AreEqual(-1, e.BatchNumber, Message);
            }
            catch
            {
                Assert.Fail(Message);
            }
        }
Ejemplo n.º 19
0
        private static BankImportTDS LoadData(Int32 ALedgerNumber, Int32 AStatementKey)
        {
            TDataBase      db            = DBAccess.Connect("LoadData");
            TDBTransaction dbtransaction = db.BeginTransaction(IsolationLevel.ReadCommitted);

            BankImportTDS MatchDS = new BankImportTDS();

            // TODO: would it help not to load all? use a_recent_match_d?
            AEpMatchAccess.LoadViaALedger(MatchDS, ALedgerNumber, dbtransaction);

            TLogging.LogAtLevel(1, "loaded " + MatchDS.AEpMatch.Rows.Count.ToString() + " a_ep_match rows");

            AEpTransactionAccess.LoadViaAEpStatement(MatchDS, AStatementKey, dbtransaction);

            dbtransaction.Rollback();

            MatchDS.AEpMatch.AcceptChanges();
            MatchDS.AEpTransaction.AcceptChanges();

            return(MatchDS);
        }
Ejemplo n.º 20
0
        public void ForeignCurrencySupplier_ExpectDocumentPostingAndPayingWorking()
        {
            //
            // Arrange
            //
            int PaymentNumber;

            List <int> DocumentIDs;
            decimal    APAccountBalanceBefore;
            decimal    BankAccountBefore;
            decimal    RevalAccountBefore;

            CommonNUnitFunctions.ResetDatabase();
            TPetraServerConnector.Connect();

            TDataBase      db          = DBAccess.Connect("ForeignCurrencySupplier_ExpectDocumentPostingPayingAndReversingWorking");
            TDBTransaction transaction = db.BeginTransaction(IsolationLevel.Serializable);

            // Act and Assert: both encapsulated in the method that gets called!
            PostAndPayForeignSupplierAPDocument("Test", out PaymentNumber, out DocumentIDs,
                                                out APAccountBalanceBefore, out BankAccountBefore, out RevalAccountBefore, db);

            transaction.Commit();
        }
Ejemplo n.º 21
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);
        }
Ejemplo n.º 22
0
        /// <summary>
        /// generate the key ministries
        /// </summary>
        /// <param name="AKeyMinCSVFile"></param>
        public static void GenerateKeyMinistries(string AKeyMinCSVFile)
        {
            XmlDocument doc = TCsv2Xml.ParseCSVFile2Xml(AKeyMinCSVFile, ",");

            XmlNode RecordNode = doc.FirstChild.NextSibling.FirstChild;

            PartnerImportExportTDS PartnerDS = new PartnerImportExportTDS();

            TDataBase      db          = DBAccess.Connect("GenerateKeyMinistries");
            TDBTransaction Transaction = db.BeginTransaction(IsolationLevel.ReadCommitted);

            // get a list of fields (all class UNIT, with unit type F)
            string    sqlGetFieldPartnerKeys = "SELECT p_partner_key_n, p_unit_name_c FROM PUB_p_unit WHERE u_unit_type_code_c = 'F'";
            DataTable FieldKeys = db.SelectDT(sqlGetFieldPartnerKeys, "keys", Transaction);

            Transaction.Rollback();

            Int32 NumberOfPartnerKeysReserved = 100;
            Int64 NextPartnerKey = TNewPartnerKey.ReservePartnerKeys(-1, ref NumberOfPartnerKeysReserved);

            while (RecordNode != null)
            {
                int FieldID =
                    Convert.ToInt32(TXMLParser.GetAttribute(RecordNode, "field")) % FieldKeys.Rows.Count;
                long FieldPartnerKey = Convert.ToInt64(FieldKeys.Rows[FieldID].ItemArray[0]);

                PUnitRow UnitRow = PartnerDS.PUnit.NewRowTyped();

                if (NumberOfPartnerKeysReserved == 0)
                {
                    NumberOfPartnerKeysReserved = 100;
                    NextPartnerKey = TNewPartnerKey.ReservePartnerKeys(-1, ref NumberOfPartnerKeysReserved);
                }

                long UnitPartnerKey = NextPartnerKey;
                NextPartnerKey++;
                NumberOfPartnerKeysReserved--;

                UnitRow.PartnerKey   = UnitPartnerKey;
                UnitRow.UnitName     = FieldKeys.Rows[FieldID].ItemArray[1].ToString() + " - " + TXMLParser.GetAttribute(RecordNode, "KeyMinName");
                UnitRow.UnitTypeCode = "KEY-MIN";
                PartnerDS.PUnit.Rows.Add(UnitRow);

                PPartnerRow PartnerRow = PartnerDS.PPartner.NewRowTyped();
                PartnerRow.PartnerKey       = UnitRow.PartnerKey;
                PartnerRow.PartnerShortName = UnitRow.UnitName;
                PartnerRow.PartnerClass     = MPartnerConstants.PARTNERCLASS_UNIT;
                PartnerRow.StatusCode       = MPartnerConstants.PARTNERSTATUS_ACTIVE;
                PartnerDS.PPartner.Rows.Add(PartnerRow);

                // add empty location so that the partner can be found in the Partner Find screen
                PPartnerLocationRow PartnerLocationRow = PartnerDS.PPartnerLocation.NewRowTyped();
                PartnerLocationRow.PartnerKey  = UnitRow.PartnerKey;
                PartnerLocationRow.LocationKey = 0;
                PartnerLocationRow.SiteKey     = 0;
                PartnerDS.PPartnerLocation.Rows.Add(PartnerLocationRow);

                // create unit hierarchy
                UmUnitStructureRow UnitStructureRow = PartnerDS.UmUnitStructure.NewRowTyped();
                UnitStructureRow.ParentUnitKey = FieldPartnerKey;
                UnitStructureRow.ChildUnitKey  = UnitRow.PartnerKey;
                PartnerDS.UmUnitStructure.Rows.Add(UnitStructureRow);

                RecordNode = RecordNode.NextSibling;
            }

            PartnerImportExportTDSAccess.SubmitChanges(PartnerDS);
        }
Ejemplo n.º 23
0
        public void Test_2YearEnds()
        {
            intLedgerNumber = CommonNUnitFunctions.CreateNewLedger();
            CommonNUnitFunctions.LoadTestDataBase("csharp\\ICT\\Testing\\lib\\MFinance\\server\\GL\\test-sql\\gl-test-year-end.sql", intLedgerNumber);
            TDataBase db = DBAccess.Connect("Test_2YearEnds");

            for (int countYear = 0; countYear < 2; countYear++)
            {
                TLogging.Log("preparing year number " + countYear.ToString());

                TDBTransaction TestBatchTransaction = db.BeginTransaction(IsolationLevel.Serializable, -1, "Test_2YearEnds.PrepareBatches");

                // accounting one gift
                string strAccountGift = "0200";
                string strAccountBank = "6200";
                TCommonAccountingTool commonAccountingTool =
                    new TCommonAccountingTool(intLedgerNumber, "NUNIT", db);
                commonAccountingTool.AddBaseCurrencyJournal();
                commonAccountingTool.JournalDescription = "Test Data accounts";
                commonAccountingTool.AddBaseCurrencyTransaction(
                    strAccountBank, "4301", "Gift Example", "Debit", MFinanceConstants.IS_DEBIT, 100);
                commonAccountingTool.AddBaseCurrencyTransaction(
                    strAccountGift, "4301", "Gift Example", "Credit", MFinanceConstants.IS_CREDIT, 100);
                TVerificationResultCollection verificationResult = new TVerificationResultCollection();
                Boolean PostedOk = commonAccountingTool.CloseSaveAndPost(verificationResult, db); // returns true if posting seemed to work
                Assert.AreEqual(true, PostedOk, "Test batch can't be posted");

                TestBatchTransaction.Commit();

                bool blnLoop = true;

                while (blnLoop)
                {
                    TDBTransaction PeriodEndTransaction = db.BeginTransaction(IsolationLevel.Serializable, -1, "Test_2YearEnds.PeriodEnd");
                    TLedgerInfo    LedgerInfo           = new TLedgerInfo(intLedgerNumber, db);

                    if (LedgerInfo.ProvisionalYearEndFlag)
                    {
                        blnLoop = false;
                    }
                    else
                    {
                        List <Int32> glBatchNumbers;
                        Boolean      stewardshipBatch;
                        TVerificationResultCollection VerificationResult;

                        TPeriodIntervalConnector.PeriodMonthEnd(
                            intLedgerNumber,
                            false,
                            out glBatchNumbers,
                            out stewardshipBatch,
                            out VerificationResult,
                            db);
                        CommonNUnitFunctions.EnsureNullOrOnlyNonCriticalVerificationResults(VerificationResult,
                                                                                            "MonthEnd gave critical error at Period" + LedgerInfo.CurrentPeriod + ":\r\n");
                    }

                    PeriodEndTransaction.Commit();
                }

                TDBTransaction transaction  = new TDBTransaction();
                bool           SubmissionOK = false;

                db.WriteTransaction(
                    ref transaction,
                    ref SubmissionOK,
                    delegate
                {
                    TLedgerInfo LedgerInfo = new TLedgerInfo(intLedgerNumber, db);

                    TLogging.Log("Closing year number " + countYear.ToString());
                    List <Int32> glBatches     = new List <int>();
                    TReallocation reallocation = new TReallocation(LedgerInfo, glBatches, transaction);
                    verificationResult         = new TVerificationResultCollection();
                    reallocation.VerificationResultCollection = verificationResult;
                    reallocation.IsInInfoMode = false;
                    //                Assert.AreEqual(1, reallocation.GetJobSize(), "Check 1 reallocation job is required"); // No job size is published by Reallocation
                    reallocation.RunOperation();

                    TYearEnd YearEndOperator       = new TYearEnd(LedgerInfo);
                    TGlmNewYearInit glmNewYearInit = new TGlmNewYearInit(LedgerInfo, countYear, YearEndOperator, transaction);
                    glmNewYearInit.VerificationResultCollection = verificationResult;
                    glmNewYearInit.IsInInfoMode = false;
                    //              Assert.Greater(glmNewYearInit.GetJobSize(), 0, "Check that NewYearInit has work to do"); // in this version, GetJobSize returns 0
                    glmNewYearInit.RunOperation();
                    YearEndOperator.SetNextPeriod(transaction);
                    SubmissionOK = true;
                });
            }

            TLedgerInfo LedgerInfo2 = new TLedgerInfo(intLedgerNumber, db);

            Assert.AreEqual(2, LedgerInfo2.CurrentFinancialYear, "After YearEnd, Ledger is in year 2");

            TAccountPeriodInfo periodInfo = new TAccountPeriodInfo(intLedgerNumber, 1);

            Assert.AreEqual(new DateTime(DateTime.Now.Year + 2,
                                         1,
                                         1), periodInfo.PeriodStartDate, "new Calendar should start with January 1st of next year");
        } // Test_2YearEnds
Ejemplo n.º 24
0
        public void TestDeleteBank()
        {
            DataSet ResponseDS = new PartnerEditTDS();
            TVerificationResultCollection VerificationResult;
            String               TextMessage;
            Boolean              CanDeletePartner;
            PPartnerRow          BankPartnerRow;
            TSubmitChangesResult result;
            Int64 PartnerKey;

            TDataBase               db          = DBAccess.Connect("TestDeleteBank");
            TDBTransaction          Transaction = db.BeginTransaction(IsolationLevel.Serializable);
            TPartnerEditUIConnector connector   = new TPartnerEditUIConnector(db);

            PartnerEditTDS MainDS = new PartnerEditTDS();

            BankPartnerRow = TCreateTestPartnerData.CreateNewBankPartner(MainDS, db);
            result         = connector.SubmitChanges(ref MainDS, ref ResponseDS, out VerificationResult);
            Assert.AreEqual(TSubmitChangesResult.scrOK, result, "create bank record");

            Transaction.Commit();
            Transaction = db.BeginTransaction(IsolationLevel.Serializable);

            // check if Bank partner can be deleted (still needs to be possible at this point)
            CanDeletePartner = TPartnerWebConnector.CanPartnerBeDeleted(BankPartnerRow.PartnerKey, out TextMessage, db);

            if (TextMessage.Length > 0)
            {
                TLogging.Log(TextMessage);
            }

            Assert.IsTrue(CanDeletePartner);

            // set up details (e.g. bank account) for this Bank so deletion is not allowed
            PBankingDetailsTable BankingDetailsTable = new PBankingDetailsTable();
            PBankingDetailsRow   BankingDetailsRow   = BankingDetailsTable.NewRowTyped();

            BankingDetailsRow.BankKey           = BankPartnerRow.PartnerKey;
            BankingDetailsRow.BankingType       = 0;
            BankingDetailsRow.BankingDetailsKey = Convert.ToInt32(TSequenceWebConnector.GetNextSequence(TSequenceNames.seq_bank_details, db));
            BankingDetailsTable.Rows.Add(BankingDetailsRow);

            Transaction.Commit();

            bool SubmitOK = false;

            db.WriteTransaction(ref Transaction, ref SubmitOK,
                                delegate
            {
                PBankingDetailsAccess.SubmitChanges(BankingDetailsTable, Transaction);
                SubmitOK = true;
            });

            // now deletion must not be possible since a bank account is set up for the bank
            CanDeletePartner = TPartnerWebConnector.CanPartnerBeDeleted(BankPartnerRow.PartnerKey, out TextMessage, db);

            if (TextMessage.Length > 0)
            {
                TLogging.Log(TextMessage);
            }

            Assert.IsTrue(!CanDeletePartner);

            // now test actual deletion of venue partner
            BankPartnerRow = TCreateTestPartnerData.CreateNewBankPartner(MainDS, db);
            PartnerKey     = BankPartnerRow.PartnerKey;
            result         = connector.SubmitChanges(ref MainDS, ref ResponseDS, out VerificationResult);
            Assert.AreEqual(TSubmitChangesResult.scrOK, result, "create bank partner for deletion");

            // check if Venue record is being deleted
            Assert.IsTrue(TPartnerWebConnector.DeletePartner(PartnerKey, out VerificationResult, db));

            // check that Bank record is really deleted
            Assert.IsTrue(!TPartnerServerLookups.VerifyPartner(PartnerKey));
        }
Ejemplo n.º 25
0
        public void TestDeletePerson()
        {
            DataSet ResponseDS = new PartnerEditTDS();
            TVerificationResultCollection VerificationResult;
            String               TextMessage;
            Boolean              CanDeletePartner;
            PPartnerRow          FamilyPartnerRow;
            PPartnerRow          UnitPartnerRow;
            PPersonRow           PersonRow;
            TSubmitChangesResult result;
            Int64 PartnerKey;

            TDataBase               db          = DBAccess.Connect("TestDeleteFamily");
            TDBTransaction          Transaction = db.BeginTransaction(IsolationLevel.Serializable);
            TPartnerEditUIConnector connector   = new TPartnerEditUIConnector(db);

            PartnerEditTDS MainDS = new PartnerEditTDS();

            // create new family, location and person
            FamilyPartnerRow = TCreateTestPartnerData.CreateNewFamilyPartner(MainDS, db);
            TCreateTestPartnerData.CreateNewLocation(FamilyPartnerRow.PartnerKey, MainDS);
            PersonRow = TCreateTestPartnerData.CreateNewPerson(MainDS,
                                                               FamilyPartnerRow.PartnerKey,
                                                               MainDS.PLocation[0].LocationKey,
                                                               "Mike",
                                                               "Mr",
                                                               0,
                                                               db);

            result = connector.SubmitChanges(ref MainDS, ref ResponseDS, out VerificationResult);
            Assert.AreEqual(TSubmitChangesResult.scrOK, result, "create family and person record");

            Transaction.Commit();
            Transaction = db.BeginTransaction(IsolationLevel.Serializable);

            // check if Family partner can be deleted (still needs to be possible at this point)
            CanDeletePartner = TPartnerWebConnector.CanPartnerBeDeleted(PersonRow.PartnerKey, out TextMessage, db);

            if (TextMessage.Length > 0)
            {
                TLogging.Log(TextMessage);
            }

            Assert.IsTrue(CanDeletePartner);

            // add a commitment for the person which means the person is not allowed to be deleted any longer
            UnitPartnerRow = TCreateTestPartnerData.CreateNewUnitPartner(MainDS, db);
            PmStaffDataTable CommitmentTable = new PmStaffDataTable();
            PmStaffDataRow   CommitmentRow   = CommitmentTable.NewRowTyped();

            CommitmentRow.Key               = Convert.ToInt32(TSequenceWebConnector.GetNextSequence(TSequenceNames.seq_staff_data, db));
            CommitmentRow.PartnerKey        = PersonRow.PartnerKey;
            CommitmentRow.StartOfCommitment = DateTime.Today.Date;
            CommitmentRow.EndOfCommitment   = DateTime.Today.AddDays(90).Date;
            CommitmentRow.OfficeRecruitedBy = UnitPartnerRow.PartnerKey;
            CommitmentRow.HomeOffice        = UnitPartnerRow.PartnerKey;
            CommitmentRow.ReceivingField    = UnitPartnerRow.PartnerKey;
            CommitmentTable.Rows.Add(CommitmentRow);

            result = connector.SubmitChanges(ref MainDS, ref ResponseDS, out VerificationResult);
            Assert.AreEqual(TSubmitChangesResult.scrOK, result, "create unit to be used in commitment");
            PmStaffDataAccess.SubmitChanges(CommitmentTable, Transaction);
            Transaction.Commit();
            Transaction = db.BeginTransaction(IsolationLevel.Serializable);

            // this should now not be allowed since person record has a commitment linked to it
            CanDeletePartner = TPartnerWebConnector.CanPartnerBeDeleted(PersonRow.PartnerKey, out TextMessage, db);

            if (TextMessage.Length > 0)
            {
                TLogging.Log(TextMessage);
            }

            Assert.IsTrue(!CanDeletePartner);

            // now test actual deletion of Person partner
            FamilyPartnerRow = TCreateTestPartnerData.CreateNewFamilyPartner(MainDS, db);
            TCreateTestPartnerData.CreateNewLocation(FamilyPartnerRow.PartnerKey, MainDS);
            PersonRow = TCreateTestPartnerData.CreateNewPerson(MainDS,
                                                               FamilyPartnerRow.PartnerKey,
                                                               MainDS.PLocation[0].LocationKey,
                                                               "Mary",
                                                               "Mrs",
                                                               0,
                                                               db);
            PartnerKey = PersonRow.PartnerKey;

            result = connector.SubmitChanges(ref MainDS, ref ResponseDS, out VerificationResult);
            Assert.AreEqual(TSubmitChangesResult.scrOK, result, "create family and person record to be deleted");

            Transaction.Commit();

            // check if Family record is being deleted
            Assert.IsTrue(TPartnerWebConnector.DeletePartner(PartnerKey, out VerificationResult));

            // check that Family record is really deleted
            Assert.IsTrue(!TPartnerServerLookups.VerifyPartner(PartnerKey));
        }
Ejemplo n.º 26
0
        public void TestDeleteFamily()
        {
            DataSet ResponseDS = new PartnerEditTDS();
            TVerificationResultCollection VerificationResult;
            String               TextMessage;
            Boolean              CanDeletePartner;
            PPartnerRow          FamilyPartnerRow;
            PFamilyRow           FamilyRow;
            PPersonRow           PersonRow;
            TSubmitChangesResult result;
            Int64 PartnerKey;

            TDataBase      db          = DBAccess.Connect("TestDeleteFamily");
            TDBTransaction Transaction = db.BeginTransaction(IsolationLevel.Serializable);

            TPartnerEditUIConnector connector = new TPartnerEditUIConnector(db);

            PartnerEditTDS MainDS = new PartnerEditTDS();

            FamilyPartnerRow = TCreateTestPartnerData.CreateNewFamilyPartner(MainDS, db);
            result           = connector.SubmitChanges(ref MainDS, ref ResponseDS, out VerificationResult);
            Assert.AreEqual(TSubmitChangesResult.scrOK, result, "Create family record");

            Transaction.Commit();
            Transaction = db.BeginTransaction(IsolationLevel.Serializable);

            // check if Family partner can be deleted (still needs to be possible at this point)
            CanDeletePartner = TPartnerWebConnector.CanPartnerBeDeleted(FamilyPartnerRow.PartnerKey, out TextMessage, db);

            if (TextMessage.Length > 0)
            {
                TLogging.Log(TextMessage);
            }

            Assert.IsTrue(CanDeletePartner);

            // add a person to the family which means the family is not allowed to be deleted any longer
            FamilyRow = (PFamilyRow)MainDS.PFamily.Rows[0];
            FamilyRow.FamilyMembers = true;
            TCreateTestPartnerData.CreateNewLocation(FamilyPartnerRow.PartnerKey, MainDS);
            result = connector.SubmitChanges(ref MainDS, ref ResponseDS, out VerificationResult);
            Assert.AreEqual(TSubmitChangesResult.scrOK, result, "create new location");

            PartnerEditTDS PersonDS = new PartnerEditTDS();

            PersonRow = TCreateTestPartnerData.CreateNewPerson(PersonDS, FamilyPartnerRow.PartnerKey,
                                                               MainDS.PLocation[0].LocationKey, "Adam", "Mr", 0, db);
            PersonRow.FamilyKey = FamilyPartnerRow.PartnerKey;
            result = connector.SubmitChanges(ref PersonDS, ref ResponseDS, out VerificationResult);
            Assert.AreEqual(TSubmitChangesResult.scrOK, result, "create person record");

            Transaction.Commit();
            Transaction = db.BeginTransaction(IsolationLevel.Serializable);

            CanDeletePartner = TPartnerWebConnector.CanPartnerBeDeleted(FamilyPartnerRow.PartnerKey, out TextMessage, db);

            if (TextMessage.Length > 0)
            {
                TLogging.Log(TextMessage);
            }

            Assert.IsTrue(!CanDeletePartner);


            // create new family and create subscription given as gift from this family: not allowed to be deleted
            FamilyPartnerRow = TCreateTestPartnerData.CreateNewFamilyPartner(MainDS, db);
            PPublicationTable PublicationTable = PPublicationAccess.LoadByPrimaryKey("TESTPUBLICATION", Transaction);

            if (PublicationTable.Count == 0)
            {
                // first check if frequency "Annual" exists and if not then create it
                if (!AFrequencyAccess.Exists("Annual", Transaction))
                {
                    // set up details (e.g. bank account) for this Bank so deletion is not allowed
                    AFrequencyTable FrequencyTable = new AFrequencyTable();
                    AFrequencyRow   FrequencyRow   = FrequencyTable.NewRowTyped();
                    FrequencyRow.FrequencyCode        = "Annual";
                    FrequencyRow.FrequencyDescription = "Annual Frequency";
                    FrequencyTable.Rows.Add(FrequencyRow);

                    AFrequencyAccess.SubmitChanges(FrequencyTable, Transaction);
                }

                // now add the publication "TESTPUBLICATION"
                PPublicationRow PublicationRow = PublicationTable.NewRowTyped();
                PublicationRow.PublicationCode = "TESTPUBLICATION";
                PublicationRow.FrequencyCode   = "Annual";
                PublicationTable.Rows.Add(PublicationRow);

                PPublicationAccess.SubmitChanges(PublicationTable, Transaction);
            }

            // make sure that "reason subscription given" exists
            if (!PReasonSubscriptionGivenAccess.Exists("FREE", Transaction))
            {
                // set up details (e.g. bank account) for this Bank so deletion is not allowed
                PReasonSubscriptionGivenTable ReasonTable = new PReasonSubscriptionGivenTable();
                PReasonSubscriptionGivenRow   ReasonRow   = ReasonTable.NewRowTyped();
                ReasonRow.Code        = "FREE";
                ReasonRow.Description = "Free Subscription";
                ReasonTable.Rows.Add(ReasonRow);

                PReasonSubscriptionGivenAccess.SubmitChanges(ReasonTable, Transaction);
            }

            // now add the publication "TESTPUBLICATION" to the first family record and indicate it was a gift from newly created family record
            PSubscriptionRow SubscriptionRow = MainDS.PSubscription.NewRowTyped();

            SubscriptionRow.PublicationCode     = "TESTPUBLICATION";
            SubscriptionRow.PartnerKey          = FamilyRow.PartnerKey;        // link subscription with original family
            SubscriptionRow.GiftFromKey         = FamilyPartnerRow.PartnerKey; // indicate that subscription is a gift from newly created family
            SubscriptionRow.ReasonSubsGivenCode = "FREE";
            MainDS.PSubscription.Rows.Add(SubscriptionRow);

            result = connector.SubmitChanges(ref MainDS, ref ResponseDS, out VerificationResult);
            Assert.AreEqual(TSubmitChangesResult.scrOK, result, "add publication to family record");

            Transaction.Commit();
            Transaction = db.BeginTransaction(IsolationLevel.Serializable);

            // this should now not be allowed since partner record has a subscription linked to it
            CanDeletePartner = TPartnerWebConnector.CanPartnerBeDeleted(FamilyPartnerRow.PartnerKey, out TextMessage, db);

            if (TextMessage.Length > 0)
            {
                TLogging.Log(TextMessage);
            }

            Assert.IsTrue(!CanDeletePartner);

            // now test actual deletion of Family partner
            FamilyPartnerRow = TCreateTestPartnerData.CreateNewFamilyPartner(MainDS, db);
            PartnerKey       = FamilyPartnerRow.PartnerKey;
            result           = connector.SubmitChanges(ref MainDS, ref ResponseDS, out VerificationResult);
            Assert.AreEqual(TSubmitChangesResult.scrOK, result, "create family record");

            Transaction.Commit();

            // check if Family record is being deleted
            Assert.IsTrue(TPartnerWebConnector.DeletePartner(PartnerKey, out VerificationResult, db));

            // check that Family record is really deleted
            Assert.IsTrue(!TPartnerServerLookups.VerifyPartner(PartnerKey));
        }
Ejemplo n.º 27
0
        public void Test_YearEnd()
        {
            intLedgerNumber = CommonNUnitFunctions.CreateNewLedger();
            TDataBase db = DBAccess.Connect("Test_YearEnd");

            TLedgerInfo LedgerInfo = new TLedgerInfo(intLedgerNumber, db);

            Assert.AreEqual(0, LedgerInfo.CurrentFinancialYear, "Before YearEnd, we should be in year 0");

            TAccountPeriodInfo periodInfo = new TAccountPeriodInfo(intLedgerNumber, 1);

            Assert.AreEqual(new DateTime(DateTime.Now.Year,
                                         1,
                                         1), periodInfo.PeriodStartDate, "Calendar from base database should start with January 1st of this year");

            CommonNUnitFunctions.LoadTestDataBase("csharp\\ICT\\Testing\\lib\\MFinance\\server\\GL\\test-sql\\gl-test-year-end.sql", intLedgerNumber);

            TDBTransaction TestBatchTransaction = db.BeginTransaction(IsolationLevel.Serializable, -1, "Test_YearEnd.PrepareBatches");

            TCommonAccountingTool commonAccountingTool =
                new TCommonAccountingTool(intLedgerNumber, "NUNIT", db);

            commonAccountingTool.AddBaseCurrencyJournal();
            commonAccountingTool.JournalDescription = "Test Data accounts";
            string strAccountGift    = "0200";
            string strAccountBank    = "6200";
            string strAccountExpense = "4100";

            // Accounting of some gifts ...
            commonAccountingTool.AddBaseCurrencyTransaction(
                strAccountBank, "4301", "Gift Example", "Debit", MFinanceConstants.IS_DEBIT, 100);
            commonAccountingTool.AddBaseCurrencyTransaction(
                strAccountBank, "4302", "Gift Example", "Debit", MFinanceConstants.IS_DEBIT, 200);
            commonAccountingTool.AddBaseCurrencyTransaction(
                strAccountBank, "4303", "Gift Example", "Debit", MFinanceConstants.IS_DEBIT, 300);

            commonAccountingTool.AddBaseCurrencyTransaction(
                strAccountGift, "4301", "Gift Example", "Credit", MFinanceConstants.IS_CREDIT, 100);
            commonAccountingTool.AddBaseCurrencyTransaction(
                strAccountGift, "4302", "Gift Example", "Credit", MFinanceConstants.IS_CREDIT, 200);
            commonAccountingTool.AddBaseCurrencyTransaction(
                strAccountGift, "4303", "Gift Example", "Credit", MFinanceConstants.IS_CREDIT, 300);


            // Accounting of some expenses ...

            commonAccountingTool.AddBaseCurrencyTransaction(
                strAccountExpense, "4301", "Expense Example", "Debit", MFinanceConstants.IS_DEBIT, 150);
            commonAccountingTool.AddBaseCurrencyTransaction(
                strAccountExpense, "4302", "Expense Example", "Debit", MFinanceConstants.IS_DEBIT, 150);
            commonAccountingTool.AddBaseCurrencyTransaction(
                strAccountExpense, "4303", "Expense Example", "Debit", MFinanceConstants.IS_DEBIT, 200);

            commonAccountingTool.AddBaseCurrencyTransaction(
                strAccountBank, "4301", "Expense Example", "Credit", MFinanceConstants.IS_CREDIT, 150);
            commonAccountingTool.AddBaseCurrencyTransaction(
                strAccountBank, "4302", "Expense Example", "Credit", MFinanceConstants.IS_CREDIT, 150);
            commonAccountingTool.AddBaseCurrencyTransaction(
                strAccountBank, "4303", "Expense Example", "Credit", MFinanceConstants.IS_CREDIT, 200);

            TVerificationResultCollection verificationResult = new TVerificationResultCollection();

            commonAccountingTool.CloseSaveAndPost(verificationResult, db); // returns true if posting seemed to work

            TestBatchTransaction.Commit();

            bool blnLoop = true;

            while (blnLoop)
            {
                TDBTransaction PeriodEndTransaction = db.BeginTransaction(IsolationLevel.Serializable, -1, "Test_2YearEnds.PeriodEnd");
                TLedgerInfo    LedgerInfo2          = new TLedgerInfo(intLedgerNumber, db);

                if (LedgerInfo2.ProvisionalYearEndFlag)
                {
                    blnLoop = false;
                }
                else
                {
                    TVerificationResultCollection VerificationResult;
                    List <Int32> glBatchNumbers;
                    Boolean      stewardshipBatch;

                    TPeriodIntervalConnector.PeriodMonthEnd(
                        intLedgerNumber, false,
                        out glBatchNumbers,
                        out stewardshipBatch,
                        out VerificationResult,
                        db);
                    CommonNUnitFunctions.EnsureNullOrOnlyNonCriticalVerificationResults(VerificationResult,
                                                                                        "Running MonthEnd gave critical error");
                }

                PeriodEndTransaction.Commit();
            }

            // check before year end that income and expense accounts are not 0
            int intYear = 0;

            CheckGLMEntry(intLedgerNumber, intYear, strAccountBank,
                          -50, 0, 50, 0, 100, 0);
            CheckGLMEntry(intLedgerNumber, intYear, strAccountExpense,
                          150, 0, 150, 0, 200, 0);
            CheckGLMEntry(intLedgerNumber, intYear, strAccountGift,
                          100, 0, 200, 0, 300, 0);

            // test that we cannot post to period 12 anymore, all periods are closed?
            LedgerInfo = new TLedgerInfo(intLedgerNumber, db);
            Assert.AreEqual(true, LedgerInfo.ProvisionalYearEndFlag, "Provisional YearEnd flag should be set");


            List <Int32>   glBatches    = new List <int>();
            TDBTransaction transaction  = new TDBTransaction();
            bool           SubmissionOK = false;

            db.WriteTransaction(
                ref transaction,
                ref SubmissionOK,
                delegate
            {
                //
                // Reallocation is never called explicitly like this - it's not really appropriate
                // because I'm about to call it again as part of YearEnd, below.
                // But a tweak in the reallocation code means that it should now cope with being called twice.
                TReallocation reallocation = new TReallocation(LedgerInfo, glBatches, transaction);
                reallocation.VerificationResultCollection = verificationResult;
                reallocation.IsInInfoMode = false;
                reallocation.RunOperation();
                SubmissionOK = true;
            });

            // check amounts after reallocation
            CheckGLMEntry(intLedgerNumber, intYear, strAccountBank,
                          -50, 0, 50, 0, 100, 0);
            CheckGLMEntry(intLedgerNumber, intYear, strAccountExpense,
                          0, -150, 0, -150, 0, -200);
            CheckGLMEntry(intLedgerNumber, intYear, strAccountGift,
                          0, -100, 0, -200, 0, -300);

            // first run in info mode
            TPeriodIntervalConnector.PeriodYearEnd(intLedgerNumber, true,
                                                   out glBatches,
                                                   out verificationResult, db);
            CommonNUnitFunctions.EnsureNullOrOnlyNonCriticalVerificationResults(verificationResult,
                                                                                "YearEnd test should not have critical errors");

            transaction = db.BeginTransaction(IsolationLevel.Serializable);
            // now run for real
            TPeriodIntervalConnector.PeriodYearEnd(intLedgerNumber, false,
                                                   out glBatches,
                                                   out verificationResult, db);
            CommonNUnitFunctions.EnsureNullOrOnlyNonCriticalVerificationResults(verificationResult,
                                                                                "YearEnd should not have critical errors");

            transaction.Commit();
            transaction = db.BeginTransaction(IsolationLevel.ReadCommitted);

            ++intYear;
            // check after year end that income and expense accounts are 0, bank account remains
            CheckGLMEntry(intLedgerNumber, intYear, strAccountBank,
                          -50, 0, 50, 0, 100, 0);
            CheckGLMEntry(intLedgerNumber, intYear, strAccountExpense,
                          0, 0, 0, 0, 0, 0);
            CheckGLMEntry(intLedgerNumber, intYear, strAccountGift,
                          0, 0, 0, 0, 0, 0);

            // also check the glm period records
            CheckGLMPeriodEntry(intLedgerNumber, intYear, 1, strAccountBank,
                                -50, 50, 100, db);
            CheckGLMPeriodEntry(intLedgerNumber, intYear, 1, strAccountExpense,
                                0, 0, 0, db);
            CheckGLMPeriodEntry(intLedgerNumber, intYear, 1, strAccountGift,
                                0, 0, 0, db);

            // 9700 is the account that the expenses and income from last year is moved to
            TGlmInfo glmInfo = new TGlmInfo(intLedgerNumber, intYear, "9700", db);

            glmInfo.Reset();
            Assert.IsTrue(glmInfo.MoveNext(), "9700 account not found");

            Assert.AreEqual(100, glmInfo.YtdActualBase);
            Assert.AreEqual(0, glmInfo.ClosingPeriodActualBase);

            LedgerInfo = new TLedgerInfo(intLedgerNumber, db);
            Assert.AreEqual(1, LedgerInfo.CurrentFinancialYear, "After YearEnd, we are in a new financial year");
            Assert.AreEqual(1, LedgerInfo.CurrentPeriod, "After YearEnd, we are in Period 1");
            Assert.AreEqual(false, LedgerInfo.ProvisionalYearEndFlag, "After YearEnd, ProvisionalYearEnd flag should not be set");

            periodInfo = new TAccountPeriodInfo(intLedgerNumber, 1, db);
            Assert.AreEqual(new DateTime(DateTime.Now.Year + 1,
                                         1,
                                         1), periodInfo.PeriodStartDate, "new Calendar should start with January 1st of next year");
            transaction.Rollback();
        }
Ejemplo n.º 28
0
        public static void Main(string[] args)
        {
            new TLogging("delivery/bin/Ict.Tools.DataMigrateStatistics.log");
            new TAppSettingsManager(false);

            string row_count_location = TAppSettingsManager.GetValue("fulldumpPath", "delivery/bin/fulldump") +
                                        Path.DirectorySeparatorChar + "_row_count.txt";

            if (File.Exists(row_count_location))
            {
                TDataBase      db          = DBAccess.Connect("DataMigrateStatistics");
                TDBTransaction Transaction = db.BeginTransaction(IsolationLevel.ReadUncommitted);

                TCmdOpts cmdLine = new TCmdOpts();
                string   xmlfile = cmdLine.GetOptValue("petraxml");

                TDataDefinitionParser parserNew = new TDataDefinitionParser(xmlfile, false);
                TDataDefinitionStore  storeNew  = new TDataDefinitionStore();
                parserNew.ParseDocument(ref storeNew, false, true);
                List <TTable> newTables = storeNew.GetTables();

                // table names and row numbers on alternate lines
                string[] checkRows = File.ReadAllLines(row_count_location);

                Console.WriteLine();
                Console.WriteLine("--- Testing all rows have loaded successfully ---");

                int  totalRows      = 0; // total number of rows in database
                int  totalCheckRows = 0; // total number of rows there should be in the database
                bool rowsMissing    = false;

                foreach (TTable newTable in newTables)
                {
                    if (newTable.strName != "s_login") // ignore this table as the row count changes everytime a connection is made to the database
                    {
                        int i = 0;
                        int rowCount;          // number of rows actually in table
                        int rowCountCheck = 0; // number of rows there should be in table

                        // count rows in table
                        string sql = "SELECT count(*) from " + newTable.strName + ";";
                        rowCount = Convert.ToInt32(db.ExecuteScalar(sql, Transaction));

                        // read how many rows there should be in the same table
                        while (i < checkRows.Length)
                        {
                            if (checkRows[i] == newTable.strName)
                            {
                                rowCountCheck = Convert.ToInt32(checkRows[i + 1]);
                                break;
                            }

                            i += 2;
                        }

                        totalRows      += rowCount;
                        totalCheckRows += rowCountCheck;

                        // if there are rows missing
                        if (rowCount != rowCountCheck)
                        {
                            Console.Write(newTable.strName + " is incomplete. ");
                            Console.WriteLine((rowCountCheck - rowCount) + " out of " + rowCountCheck + " rows did not load!");
                            rowsMissing = true;
                        }
                    }
                }

                // if all rows are present
                if (!rowsMissing)
                {
                    Console.WriteLine("All rows successfully loaded.");
                }

                // write a summary of the number of rows successfully loaded
                Console.WriteLine();
                Console.WriteLine("--- Total number of rows loaded ---");
                Console.WriteLine(totalRows + " out of " + totalCheckRows + " rows loaded successfully.");
                string percentage = (decimal.Divide(totalRows * 100, totalCheckRows)).ToString("#.##");
                Console.WriteLine(percentage + "%");
                Console.WriteLine();

                db.CloseDBConnection();
            }
            else
            {
                TLogging.Log("Warning: unable to perform a row count test. _row_count.txt is missing from the folder .../delivery/bin/fulldump.");
                TLogging.Log("");
            }
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Initialize the Petra server and connect to the database
        /// </summary>
        /// <param name="AConfigName">just provide the server config file, plus AutoLogin and AutoLoginPasswd</param>
        public static TServerManager Connect(string AConfigName)
        {
            TDBTransaction LoginTransaction;
            bool           CommitLoginTransaction = false;
            bool           SystemEnabled;
            string         WelcomeMessage;
            Int32          ClientID;
            Int64          SiteKey;

            if (!File.Exists(AConfigName) && (AConfigName.Length > 0))
            {
                TLogging.Log("cannot find config file " + Path.GetFullPath(AConfigName));
                Environment.Exit(-1);
            }

            TSession.InitThread("NUnitPetraServer.TPetraServerConnector.Connect", AConfigName);

            CommonNUnitFunctions.InitRootPath();

            Catalog.Init();
            TServerManager.TheServerManager = new TServerManager();

            ErrorCodeInventory.Init();

            // initialise the cached tables and the delegates
            TSetupDelegates.Init();

            TDataBase db = DBAccess.Connect(
                "Ict.Testing.NUnitPetraServer.TPetraServerConnector.Connect DB Connection");

            // we need a serializable transaction, to store the session
            LoginTransaction = db.BeginTransaction(IsolationLevel.Serializable);

            try
            {
                TClientManager.PerformLoginChecks(TAppSettingsManager.GetValue("AutoLogin").ToUpper(),
                                                  TAppSettingsManager.GetValue("AutoLoginPasswd"),
                                                  "NUNITTEST", "127.0.0.1", out SystemEnabled, LoginTransaction);

                CommitLoginTransaction = true;
            }
            catch (EPetraSecurityException)
            {
                // We need to set this flag to true here to get the failed login to be stored in the DB!!!
                CommitLoginTransaction = true;
            }
            finally
            {
                if (CommitLoginTransaction)
                {
                    LoginTransaction.Commit();
                }
                else
                {
                    LoginTransaction.Rollback();
                }
            }

            TConnectedClient CurrentClient = TClientManager.ConnectClient(
                TAppSettingsManager.GetValue("AutoLogin").ToUpper(),
                TAppSettingsManager.GetValue("AutoLoginPasswd"),
                "NUNITTEST", "127.0.0.1",
                TFileVersionInfo.GetApplicationVersion().ToVersion(),
                TClientServerConnectionType.csctLocal,
                out ClientID,
                out WelcomeMessage,
                out SystemEnabled,
                out SiteKey,
                db);

            // the following values are stored in the session object
            DomainManager.GClientID     = ClientID;
            DomainManager.CurrentClient = CurrentClient;
            DomainManager.GSiteKey      = SiteKey;

            TSetupDelegates.Init();

            db.CloseDBConnection();

            return((TServerManager)TServerManager.TheServerManager);
        }
Ejemplo n.º 30
0
        public void TestNewPartnerWithLocation0()
        {
            TDataBase               db          = DBAccess.Connect("TestNewPartnerWithLocation0");
            TDBTransaction          Transaction = db.BeginTransaction(IsolationLevel.Serializable);
            TPartnerEditUIConnector connector   = new TPartnerEditUIConnector(db);

            PartnerEditTDS MainDS = new PartnerEditTDS();

            PPartnerRow PartnerRow = TCreateTestPartnerData.CreateNewFamilyPartner(MainDS, db);

            PPartnerLocationRow PartnerLocationRow = MainDS.PPartnerLocation.NewRowTyped();

            PartnerLocationRow.SiteKey     = DomainManager.GSiteKey;
            PartnerLocationRow.PartnerKey  = PartnerRow.PartnerKey;
            PartnerLocationRow.LocationKey = 0;
            MainDS.PPartnerLocation.Rows.Add(PartnerLocationRow);

            DataSet ResponseDS = new PartnerEditTDS();
            TVerificationResultCollection VerificationResult;

            TSubmitChangesResult result = connector.SubmitChanges(ref MainDS, ref ResponseDS, out VerificationResult);

            CommonNUnitFunctions.EnsureNullOrOnlyNonCriticalVerificationResults(VerificationResult,
                                                                                "There was a critical error when saving:");

            Assert.AreEqual(TSubmitChangesResult.scrOK, result, "Create a partner with location 0");

            Transaction.Commit();
            Transaction = db.BeginTransaction(IsolationLevel.Serializable);

            TCreateTestPartnerData.CreateNewLocation(PartnerRow.PartnerKey, MainDS);

            // remove location 0, same is done in csharp\ICT\Petra\Client\MCommon\logic\UC_PartnerAddresses.cs TUCPartnerAddressesLogic::AddRecord
            // Check if record with PartnerLocation.LocationKey = 0 is around > delete it
            DataRow PartnerLocationRecordZero =
                MainDS.PPartnerLocation.Rows.Find(new object[] { PartnerRow.PartnerKey, DomainManager.GSiteKey, 0 });

            if (PartnerLocationRecordZero != null)
            {
                DataRow LocationRecordZero = MainDS.PLocation.Rows.Find(new object[] { DomainManager.GSiteKey, 0 });

                if (LocationRecordZero != null)
                {
                    LocationRecordZero.Delete();
                }

                PartnerLocationRecordZero.Delete();
            }

            ResponseDS = new PartnerEditTDS();
            result     = connector.SubmitChanges(ref MainDS, ref ResponseDS, out VerificationResult);

            CommonNUnitFunctions.EnsureNullOrOnlyNonCriticalVerificationResults(VerificationResult,
                                                                                "There was a critical error when saving:");

            Assert.AreEqual(TSubmitChangesResult.scrOK, result, "Replace location 0 of partner");

            Assert.AreEqual(1, MainDS.PPartnerLocation.Rows.Count, "the partner should only have one location in the dataset");

            Transaction.Commit();

            // get all addresses of the partner
            TDBTransaction ReadTransaction = new TDBTransaction();

            db.ReadTransaction(
                ref ReadTransaction,
                delegate
            {
                PPartnerLocationTable testPartnerLocations = PPartnerLocationAccess.LoadViaPPartner(PartnerRow.PartnerKey, ReadTransaction);
                Assert.AreEqual(1, testPartnerLocations.Rows.Count, "the partner should only have one location");
                Assert.Greater(testPartnerLocations[0].LocationKey, 0, "TPartnerEditUIConnector SubmitChanges returns valid location key");
            });
        }