public void TestFileHeaderReplace()
        {
            string fileName           = TAppSettingsManager.GetValue("Server.PathTemp") + Path.DirectorySeparatorChar + "TestGenHOSAFileHeaderReplace.csv";
            int    PeriodNumber       = 4;
            string StandardCostCentre = "4300";
            string CostCentre         = "78";
            string Currency           = "USD";

            StreamWriter sw = new StreamWriter(fileName);

            sw.WriteLine("/** Header **,4,4300,78,18/01/2013,USD");
            sw.Close();

            TVerificationResultCollection VerificationResults = new TVerificationResultCollection();

            string TableForExportHeader = "/** Header **" + "," +
                                          PeriodNumber.ToString() + "," +
                                          StandardCostCentre + "," +
                                          CostCentre + "," +
                                          DateTime.Today.ToShortDateString() + "," +
                                          Currency;

            TGenHOSAFilesReportsWebConnector.ReplaceHeaderInFile(fileName, TableForExportHeader, ref VerificationResults);

            CommonNUnitFunctions.EnsureNullOrOnlyNonCriticalVerificationResults(VerificationResults,
                                                                                "Header Replacement in File Failed!");

            File.Delete(fileName);
        }
Esempio n. 2
0
        /// <summary>
        /// this function will import admin fees if there are no admin fees in the database yet
        /// </summary>
        private void ImportAdminFees()
        {
            AFeesPayableTable    FeesPayableTable    = null;
            AFeesReceivableTable FeesReceivableTable = null;
            TDBTransaction       Transaction         = null;

            DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted, ref Transaction,
                                                                      delegate
            {
                AFeesPayableRow template = new AFeesPayableTable().NewRowTyped(false);
                template.LedgerNumber    = FLedgerNumber;
                template.FeeCode         = MainFeesPayableCode;

                FeesPayableTable = AFeesPayableAccess.LoadUsingTemplate(template, Transaction);

                AFeesReceivableRow template1 = new AFeesReceivableTable().NewRowTyped(false);
                template1.LedgerNumber       = FLedgerNumber;
                template1.FeeCode            = MainFeesReceivableCode;

                FeesReceivableTable = AFeesReceivableAccess.LoadUsingTemplate(template1, Transaction);
            });

            if (FeesPayableTable.Count == 0)
            {
                CommonNUnitFunctions.LoadTestDataBase("csharp\\ICT\\Testing\\lib\\MFinance\\GL\\" +
                                                      "test-sql\\gl-test-feespayable-data.sql", FLedgerNumber);
            }

            if (FeesReceivableTable.Count == 0)
            {
                CommonNUnitFunctions.LoadTestDataBase("csharp\\ICT\\Testing\\lib\\MFinance\\GL\\" +
                                                      "test-sql\\gl-test-feesreceivable-data.sql");
            }
        }
Esempio n. 3
0
        private AAPInfos PostSimpleAPDocument(decimal AAmount, string ADocumentCode, string ANarrative,
                                              out decimal AAPAccountBalanceBefore, out decimal ABankAccountBefore, out decimal AExpAccountBefore,
                                              out List <int> ADocumentIds)
        {
            TVerificationResultCollection VerificationResult;

            ADocumentIds = new List <int>();

            AAPInfos APInfos = APTestsArrangement(SUPPLIER_PARTNER_KEY, AAmount, null, ADocumentCode, ANarrative);

            // Save the current amount on the AP account
            AAPAccountBalanceBefore = new TGet_GLM_Info(FLedgerNumber,
                                                        APInfos.ApAccountCode, APInfos.CostCentreCode).YtdActual;
            ABankAccountBefore = new TGet_GLM_Info(FLedgerNumber,
                                                   APInfos.BankAccount, APInfos.CostCentreCode).YtdActual;

            AExpAccountBefore = new TGet_GLM_Info(FLedgerNumber,
                                                  APInfos.ApDS.AApSupplier[0].DefaultExpAccount,
                                                  APInfos.CostCentreCode).YtdActual;

            VerificationResult = PostAPDocument(APInfos.ApDS, APInfos.PeriodStartDate, ref ADocumentIds);
            CommonNUnitFunctions.EnsureNullOrEmptyVerificationResult(VerificationResult);   // Guard Assert

            //
            // Guard Assert: Posting OK?
            //
            decimal ExpAccountAfter = new TGet_GLM_Info(FLedgerNumber,
                                                        APInfos.ApDS.AApSupplier[0].DefaultExpAccount,
                                                        APInfos.ApDS.AApSupplier[0].DefaultCostCentre).YtdActual;

            Assert.AreEqual(AAmount, ExpAccountAfter - AExpAccountBefore, "after posting the invoice, the expense account should be debited");

            return(APInfos);
        }
Esempio n. 4
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");
        }
Esempio n. 5
0
        public void TestKeepAliveWithoutTimeout()
        {
            CommonNUnitFunctions.StartOpenPetraServer("-D:Server.ClientKeepAliveTimeoutAfterXSeconds_LAN=10");

            try
            {
                // check number of connected clients
                string connectedClientsMessage = CommonNUnitFunctions.OpenPetraServerAdminConsole("ConnectedClients");
                StringAssert.Contains("* no connected Clients *", connectedClientsMessage, "there should not be any clients connected at the moment");

                TPetraConnector.Connect("../../etc/TestClient.config", "<add key=\"ServerObjectKeepAliveIntervalInSeconds\" value=\"5\"/>");

                connectedClientsMessage = CommonNUnitFunctions.OpenPetraServerAdminConsole("ConnectedClients");
                StringAssert.Contains("Connected since", connectedClientsMessage, "there should be one client connected");

                Thread.Sleep(Convert.ToInt32(TimeSpan.FromSeconds(15.0).TotalMilliseconds));

                connectedClientsMessage = CommonNUnitFunctions.OpenPetraServerAdminConsole("ConnectedClients");
                StringAssert.Contains("Connected since", connectedClientsMessage, "the client should still be connected, no timeout");

                TPetraConnector.Disconnect();

                connectedClientsMessage = CommonNUnitFunctions.OpenPetraServerAdminConsole("ConnectedClients");
                StringAssert.Contains("* no connected Clients *", connectedClientsMessage, "there should not be any clients connected anymore");
            }
            finally
            {
                // clean up
                CommonNUnitFunctions.nant("stopServer", false);
            }
        }
Esempio n. 6
0
        /// connect to the server
        public static void Connect(string AConfigName)
        {
            TUnhandledThreadExceptionHandler UnhandledThreadExceptionHandler;

            // Set up Handlers for 'UnhandledException'
            // Note: BOTH handlers are needed for a WinForms Application!!!
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(ExceptionHandling.UnhandledExceptionHandler);
            UnhandledThreadExceptionHandler             = new TUnhandledThreadExceptionHandler();

            Application.ThreadException += new ThreadExceptionEventHandler(UnhandledThreadExceptionHandler.OnThreadException);

            new TAppSettingsManager(AConfigName);

            CommonNUnitFunctions.InitRootPath();

            Catalog.Init();
            TClientTasksQueue.ClientTasksInstanceType       = typeof(TClientTaskInstance);
            TConnectionManagementBase.ConnectorType         = typeof(TConnector);
            TConnectionManagementBase.GConnectionManagement = new TConnectionManagement();

            new TClientSettings();
            TClientInfo.InitializeUnit();
            TCacheableTablesManager.InitializeUnit();

            // Set up Data Validation Delegates
            TSharedValidationHelper.SharedGetDataDelegate                   = @TServerLookup.TMCommon.GetData;
            TSharedPartnerValidationHelper.VerifyPartnerDelegate            = @TServerLookup.TMPartner.VerifyPartner;
            TSharedFinanceValidationHelper.GetValidPostingDateRangeDelegate = @TServerLookup.TMFinance.GetCurrentPostingRangeDates;
            TSharedFinanceValidationHelper.GetValidPeriodDatesDelegate      = @TServerLookup.TMFinance.GetCurrentPeriodDates;

            Connect(TAppSettingsManager.GetValue("AutoLogin"), TAppSettingsManager.GetValue("AutoLoginPasswd"),
                    TAppSettingsManager.GetInt64("SiteKey"));
        }
Esempio n. 7
0
        public void TestKeepAliveWithTimeout()
        {
            // TODORemoting
            // set keep alive signal on client and server in a way that the server thinks the client has gone away
            CommonNUnitFunctions.StartOpenPetraServer("-D:Server.ClientKeepAliveTimeoutAfterXSeconds_LAN=10");

            try
            {
                TPetraConnector.Connect("../../etc/TestClient.config", "<add key=\"ServerObjectKeepAliveIntervalInSeconds\" value=\"20\"/>");

                string connectedClientsMessage = CommonNUnitFunctions.OpenPetraServerAdminConsole("ConnectedClients");
                StringAssert.Contains("Connected since", connectedClientsMessage, "there should be one client connected");

                Thread.Sleep(Convert.ToInt32(TimeSpan.FromSeconds(15.0).TotalMilliseconds));

                connectedClientsMessage = CommonNUnitFunctions.OpenPetraServerAdminConsole("ConnectedClients");
                StringAssert.Contains("* no connected Clients *",
                                      connectedClientsMessage,
                                      "there should not be any clients connected anymore after the client got disconnected due to timeout");
            }
            finally
            {
                // clean up
                CommonNUnitFunctions.nant("stopServer", false);
            }
        }
Esempio n. 8
0
        public void Test_01_GL_Batch_Import()
        {
            Hashtable requestParams = new Hashtable();

            requestParams.Add("ALedgerNumber", FLedgerNumber);
            requestParams.Add("Delimiter", ";");
            requestParams.Add("DateFormatString", "dd/MM/yyyy");
            requestParams.Add("DatesMayBeIntegers", false);
            requestParams.Add("NumberFormat", "European");
            requestParams.Add("NewLine", Environment.NewLine);

            string strContent = CommonNUnitFunctions.LoadCSVFileToString("csharp\\ICT\\Testing\\lib\\MFinance\\GL\\" +
                                                                         "test-csv\\glbatch-import.csv");

            strContent = strContent.Replace("31/07/2010", "31/07/" + DateTime.Now.Year.ToString());
            strContent = strContent.Replace("02/07/2010", "02/07/" + DateTime.Now.Year.ToString());
            strContent = strContent.Replace("{ledgernumber}", FLedgerNumber.ToString());

            TVerificationResultCollection verificationResult;
            bool refreshRequired;

            bool importSuccess = TGLTransactionWebConnector.ImportGLBatches(requestParams, strContent, out refreshRequired, out verificationResult);

            if (!TVerificationHelper.IsNullOrOnlyNonCritical(verificationResult))
            {
                TLogging.Log(verificationResult.BuildVerificationResultString());
            }

            Assert.IsTrue(importSuccess, "Import glbatch-import.csv done well ....");
        }
Esempio n. 9
0
        private TVerificationResultCollection ReversePayment(int APaymentNumber, DateTime APeriodEndDate,
                                                             List <int> ADocumentIds, AccountsPayableTDS AApDS)
        {
            string AssertFailMessage = "Failed to reverse AP payment: ";
            TVerificationResultCollection VerificationResult;

            List <Int32> glBatchNumbers;

            // "Un-pay" the specified invoice
            if (!TAPTransactionWebConnector.ReversePayment(FLedgerNumber,
                                                           APaymentNumber,
                                                           APeriodEndDate,
                                                           out glBatchNumbers,
                                                           out VerificationResult))
            {
                Assert.Fail(AssertFailMessage +
                            VerificationResult.BuildVerificationResultString());
            }

            CommonNUnitFunctions.EnsureNullOrEmptyVerificationResult(VerificationResult, AssertFailMessage);   // Guard Assert

            // "Un-post" the specified invoice - returning it to "Approved" status!
            ADocumentIds[0] += 2; // The invoice I posted was reversed, and a duplicate now exists with an Id 2 greater than the original.

            return(PostAPDocument(AApDS, APeriodEndDate, ref ADocumentIds, true));
        }
Esempio n. 10
0
        public void Init()
        {
            CommonNUnitFunctions.ResetDatabase();
            TPetraServerConnector.Connect("../../etc/TestServer.config");

            TDataBase   db       = DBAccess.Connect("AddressToolsTest");
            PPartnerRow Partner1 = TCreateTestPartnerData.CreateNewFamilyPartner(MainDS, db);

            TestPartnerKey = Partner1.PartnerKey;

            //Guard assert: ensure database has been properly reset
            TDBTransaction ATransaction = new TDBTransaction();
            DataTable      ResultTable  = null;
            string         Query        = string.Format("SELECT * FROM p_location WHERE p_site_key_n = {0} AND p_location_key_i = {1}",
                                                        DomainManager.GSiteKey,
                                                        LocationKey);

            db.ReadTransaction(
                ref ATransaction,
                delegate
            {
                ResultTable = ATransaction.DataBaseObj.SelectDT(Query, "CheckLocations", ATransaction);
            });
            Assert.AreEqual(0, ResultTable.Rows.Count);
        }
Esempio n. 11
0
        private TVerificationResultCollection PostAPDocument(AccountsPayableTDS AMainDS, DateTime APostingDate,
                                                             ref List <int> ADocumentIds, bool AReversal = false)
        {
            string AssertFailMessage = AReversal ? "Failed to post AP document reversal: " : "Problems posting AP document: ";
            TVerificationResultCollection VerificationResult;

            if (!AReversal)
            {
                ADocumentIds.Add(AMainDS.AApDocument[0].ApDocumentId);
            }

            Int32 glBatchNumber;

            if (!TAPTransactionWebConnector.PostAPDocuments(FLedgerNumber,
                                                            ADocumentIds,
                                                            APostingDate,
                                                            AReversal,
                                                            out glBatchNumber,
                                                            out VerificationResult))
            {
                Assert.Fail(AssertFailMessage +
                            VerificationResult.BuildVerificationResultString());
            }

            CommonNUnitFunctions.EnsureNullOrEmptyVerificationResult(VerificationResult, AssertFailMessage);   // Guard Assert

            return(VerificationResult);
        }
Esempio n. 12
0
        /// <summary>
        /// setup a ledger with simple test data
        /// </summary>
        public static int SetupTestLedgerWithPostedBatches()
        {
            // create a new ledger
            int LedgerNumber = CommonNUnitFunctions.CreateNewLedger();

            // post a sample batch
            TCommonAccountingTool commonAccountingTool =
                new TCommonAccountingTool(LedgerNumber, "NUNIT");

            commonAccountingTool.AddBaseCurrencyJournal();
            commonAccountingTool.JournalDescription = "Test Data accounts";
            string strAccountBank     = "6000";
            string StandardCostCentre = TGLTransactionWebConnector.GetStandardCostCentre(LedgerNumber);

            // Accounting of a start balance
            commonAccountingTool.AddBaseCurrencyTransaction(
                "6200", StandardCostCentre, "Start Balance", "Debit", MFinanceConstants.IS_DEBIT, 40);
            commonAccountingTool.AddBaseCurrencyTransaction(
                "9700", StandardCostCentre, "Start Balance", "Credit", MFinanceConstants.IS_CREDIT, 40);
            // Accounting of some gifts ...
            commonAccountingTool.AddBaseCurrencyTransaction(
                strAccountBank, StandardCostCentre, "Gift Example", "Debit", MFinanceConstants.IS_DEBIT, 100);
            commonAccountingTool.AddBaseCurrencyTransaction(
                "0100", StandardCostCentre, "Gift Example", "Credit", MFinanceConstants.IS_CREDIT, 100);
            // Accounting of some expense ...
            commonAccountingTool.AddBaseCurrencyTransaction(
                strAccountBank, StandardCostCentre, "Expense Example", "Credit", MFinanceConstants.IS_CREDIT, 20);
            commonAccountingTool.AddBaseCurrencyTransaction(
                "4200", StandardCostCentre, "Expense Example", "Debit", MFinanceConstants.IS_DEBIT, 20);
            commonAccountingTool.CloseSaveAndPost(); // returns true if posting seemed to work

            return(LedgerNumber);
        }
Esempio n. 13
0
        private void PrepareTestCaseData()
        {
            TDBTransaction Transaction = null;
            bool           AccountTestCasesAvailable    = false;
            bool           CostCentreTestCasesAvailable = false;

            DBAccess.GDBAccessObj.BeginAutoReadTransaction(ref Transaction,
                                                           delegate
            {
                // Check if some special test data are available - otherwise load ...
                AccountTestCasesAvailable    = AAccountAccess.Exists(LedgerNumber, "6001", Transaction);
                CostCentreTestCasesAvailable = ACostCentreAccess.Exists(LedgerNumber, "4301", Transaction);
            });

            if (!AccountTestCasesAvailable)
            {
                CommonNUnitFunctions.LoadTestDataBase("csharp\\ICT\\Testing\\lib\\MFinance\\GL\\" +
                                                      "test-sql\\gl-test-account-data.sql", LedgerNumber);
            }

            if (!CostCentreTestCasesAvailable)
            {
                CommonNUnitFunctions.LoadTestDataBase("csharp\\ICT\\Testing\\lib\\MFinance\\GL\\" +
                                                      "test-sql\\gl-test-costcentre-data.sql", LedgerNumber);
            }
        }
        public void TestGenerateHOSAFiles()
        {
            int    LedgerNumber   = FLedgerNumber;
            int    PeriodNumber   = 4;
            int    IchNumber      = 1;
            string CostCentre     = "73";
            String CurrencySelect = MFinanceConstants.CURRENCY_BASE;
            string FileName       = TAppSettingsManager.GetValue("Server.PathTemp") + Path.DirectorySeparatorChar + "TestGenHOSAFile.csv";
            TVerificationResultCollection VerificationResults;

            TGenHOSAFilesReportsWebConnector.GenerateHOSAFiles(LedgerNumber,
                                                               PeriodNumber,
                                                               IchNumber,
                                                               CostCentre,
                                                               CurrencySelect,
                                                               FileName,
                                                               out VerificationResults);

            CommonNUnitFunctions.EnsureNullOrOnlyNonCriticalVerificationResults(VerificationResults,
                                                                                "HOSA File Generation Failed!");

            Assert.IsTrue(File.Exists(FileName),
                          "HOSA File did not create!");

            File.Delete(FileName);
        }
        public void Test_TAccountPeriodToNewYear()
        {
            // create new ledger which is in year 2010
            int intLedgerNumber2010 = CommonNUnitFunctions.CreateNewLedger(new DateTime(2010, 1, 1));

            // We are in 2010 and this and 2011 is not a leap year
            TVerificationResultCollection verificationResult     = new TVerificationResultCollection();
            TAccountPeriodToNewYear       accountPeriodToNewYear = new TAccountPeriodToNewYear(intLedgerNumber2010);

            accountPeriodToNewYear.VerificationResultCollection = verificationResult;
            accountPeriodToNewYear.IsInInfoMode = false;

            // RunEndOfPeriodOperation ...
            accountPeriodToNewYear.RunOperation();

            TAccountPeriodInfo accountPeriodInfo = new TAccountPeriodInfo(intLedgerNumber2010);

            accountPeriodInfo.AccountingPeriodNumber = 2;
            Assert.AreEqual(2011, accountPeriodInfo.PeriodStartDate.Year, "Test of the year");
            Assert.AreEqual(28, accountPeriodInfo.PeriodEndDate.Day, "Test of the Feb. 28th");

            // Switch to 2012 - this is a leap year ...
            accountPeriodToNewYear = new TAccountPeriodToNewYear(intLedgerNumber2010);
            accountPeriodToNewYear.IsInInfoMode = false;
            accountPeriodToNewYear.RunOperation();

            accountPeriodInfo = new TAccountPeriodInfo(intLedgerNumber2010);
            accountPeriodInfo.AccountingPeriodNumber = 2;
            Assert.AreEqual(29, accountPeriodInfo.PeriodEndDate.Day, "Test of the Feb. 29th");
        }
Esempio n. 16
0
        public void Test_SwitchToNextMonth()
        {
            FLedgerNumber = CommonNUnitFunctions.CreateNewLedger();
            TLedgerInfo ledgerInfo = new TLedgerInfo(FLedgerNumber);
            int         counter    = 0;

            do
            {
                Int32 CurrentPeriod = ledgerInfo.CurrentPeriod;
                ++counter;
                Assert.Greater(20, counter, "Too many loops");

                // Set revaluation flag ...
                new TLedgerInitFlagHandler(FLedgerNumber,
                                           TLedgerInitFlagEnum.Revaluation).Flag = true;

                // Run MonthEnd ...
                TVerificationResultCollection verificationResult;
                bool blnHasErrors = TPeriodIntervalConnector.PeriodMonthEnd(
                    FLedgerNumber, false, out verificationResult);

                if (!ledgerInfo.ProvisionalYearEndFlag)
                {
                    Assert.AreEqual(CurrentPeriod + 1,
                                    ledgerInfo.CurrentPeriod, "Period increment");
                }

                Assert.IsFalse(blnHasErrors, "Month end without any error");
                System.Diagnostics.Debug.WriteLine("Counter: " + counter.ToString());
            } while (!ledgerInfo.ProvisionalYearEndFlag);
        }
Esempio n. 17
0
        /// <summary>
        /// This will import a test gift batch, and post it.
        /// </summary>
        public static int ImportAndPostGiftBatch(DateTime AGiftDateEffective, TDataBase ADataBase)
        {
            TGiftImporting importer = new TGiftImporting();

            string testFile = TAppSettingsManager.GetValue("GiftBatch.file",
                                                           CommonNUnitFunctions.rootPath + "/csharp/ICT/Testing/lib/MFinance/SampleData/sampleGiftBatch.csv");

            TLogging.Log(testFile);

            StreamReader sr          = new StreamReader(testFile);
            string       FileContent = sr.ReadToEnd();

            sr.Close();

            FileContent = FileContent.Replace("{ledgernumber}", FLedgerNumber.ToString());
            FileContent = FileContent.Replace("{thisyear}-01-01", AGiftDateEffective.ToString("yyyy-MM-dd"));

            Hashtable parameters = new Hashtable();

            parameters.Add("Delimiter", ",");
            parameters.Add("ALedgerNumber", FLedgerNumber);
            parameters.Add("DateFormatString", "yyyy-MM-dd");
            parameters.Add("DatesMayBeIntegers", false);
            parameters.Add("NumberFormat", "American");
            parameters.Add("NewLine", Environment.NewLine);

            TVerificationResultCollection VerificationResult;
            GiftBatchTDSAGiftDetailTable  NeedRecipientLedgerNumber;
            bool refreshRequired;

            importer.ImportGiftBatches(parameters, FileContent, out NeedRecipientLedgerNumber, out refreshRequired, out VerificationResult, ADataBase);

            CommonNUnitFunctions.EnsureNullOrOnlyNonCriticalVerificationResults(VerificationResult,
                                                                                "error when importing gift batch:");

            int BatchNumber = importer.GetLastGiftBatchNumber();

            Assert.AreNotEqual(-1, BatchNumber, "Should have imported the gift batch and return a valid batch number");

            Int32 generatedGlBatchNumber;

            if (!TGiftTransactionWebConnector.PostGiftBatch(FLedgerNumber, BatchNumber, out generatedGlBatchNumber, out VerificationResult, ADataBase))
            {
                string VerifResStr;

                if (VerificationResult != null)
                {
                    VerifResStr = ": " + VerificationResult.BuildVerificationResultString();
                }
                else
                {
                    VerifResStr = String.Empty;
                }

                Assert.Fail("Gift Batch was not posted" + VerifResStr);
            }

            return(BatchNumber);
        }
Esempio n. 18
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();
        }
Esempio n. 19
0
        /// <summary>
        /// Initialize the Petra server and connect to the database.
        /// this overload looks for the config file itself
        /// </summary>
        public static TServerManager Connect()
        {
            CommonNUnitFunctions.InitRootPath();

            string strNameConfig = CommonNUnitFunctions.rootPath + "etc/TestServer.config";

            return(Connect(strNameConfig));
        }
        public void Init()
        {
            TPetraServerConnector.Connect();
            FLedgerNumber = CommonNUnitFunctions.CreateNewLedger();
            FledgerInfo   = new TLedgerInfo(FLedgerNumber);

            System.Diagnostics.Debug.WriteLine("Init: " + this.ToString());
        }
Esempio n. 21
0
 public void Init()
 {
     Catalog.Init();
     new TLogging("../../log/test.log");
     new TAppSettingsManager("../../etc/TestServer.config");
     CommonNUnitFunctions.InitRootPath();
     CommonNUnitFunctions.StartOpenPetraServer();
 }
Esempio n. 22
0
        public void TestGenerateICHEmail()
        {
            TVerificationResultCollection VerificationResults = new TVerificationResultCollection();

            int    PeriodNumber        = 5;
            int    ICHProcessingNumber = 1;
            int    CurrencyType        = 1; //base
            string FileName            = TAppSettingsManager.GetValue("Server.PathTemp") + Path.DirectorySeparatorChar + "TestGenerateICHEmail.csv";
            bool   SendEmail           = true;

            // make sure there is a valid email destination
            if (TGenFilesReports.GetICHEmailAddress(null).Length == 0)
            {
                string sqlStatement =
                    String.Format("INSERT INTO PUB_{0}({1},{2},{3},{4}) VALUES (?,?,?,?)",
                                  AEmailDestinationTable.GetTableDBName(),
                                  AEmailDestinationTable.GetFileCodeDBName(),
                                  AEmailDestinationTable.GetConditionalValueDBName(),
                                  AEmailDestinationTable.GetPartnerKeyDBName(),
                                  AEmailDestinationTable.GetEmailAddressDBName());

                OdbcParameter parameter;

                List <OdbcParameter> parameters = new List <OdbcParameter>();
                parameter       = new OdbcParameter("name", OdbcType.VarChar);
                parameter.Value = MFinanceConstants.EMAIL_FILE_CODE_STEWARDSHIP;
                parameters.Add(parameter);
                parameter       = new OdbcParameter("condition", OdbcType.VarChar);
                parameter.Value = Convert.ToInt64(MFinanceConstants.ICH_COST_CENTRE) / 100;
                parameters.Add(parameter);
                parameter       = new OdbcParameter("partnerkey", OdbcType.Int);
                parameter.Value = Convert.ToInt64(MFinanceConstants.ICH_COST_CENTRE) * 10000;
                parameters.Add(parameter);
                parameter       = new OdbcParameter("email", OdbcType.VarChar);
                parameter.Value = TAppSettingsManager.GetValue("ClearingHouse.EmailAddress");
                parameters.Add(parameter);

                bool           SubmissionOK  = true;
                TDBTransaction DBTransaction = null;
                DBAccess.GDBAccessObj.BeginAutoTransaction(IsolationLevel.Serializable, ref DBTransaction, ref SubmissionOK,
                                                           delegate
                {
                    DBAccess.GDBAccessObj.ExecuteNonQuery(sqlStatement, DBTransaction, parameters.ToArray());
                    DBAccess.GDBAccessObj.CommitTransaction();
                });
            }

            TGenFilesReports.GenerateStewardshipFile(FLedgerNumber,
                                                     PeriodNumber,
                                                     ICHProcessingNumber,
                                                     CurrencyType,
                                                     FileName,
                                                     SendEmail,
                                                     out VerificationResults);

            CommonNUnitFunctions.EnsureNullOrOnlyNonCriticalVerificationResults(VerificationResults,
                                                                                "Performing ICH Email File Generation Failed!");
        }
Esempio n. 23
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");
            });
        }
Esempio n. 24
0
        public void TestAnnualReceipt()
        {
            CommonNUnitFunctions.ResetDatabase();

            // import a test gift batch
            TVerificationResultCollection VerificationResult;

            if (!ImportAndPostGiftBatch(FLedgerNumber, out VerificationResult))
            {
                Assert.Fail("ImportAndPostGiftBatch failed: " + VerificationResult.BuildVerificationResultString());
            }

            // TODO test reversed gifts

            string formletterTemplateFile = TAppSettingsManager.GetValue("ReceiptTemplate.file",
                                                                         "../../csharp/ICT/Testing/lib/MFinance/SampleData/AnnualReceiptTemplate.html");
            Encoding     encodingOfHTMLfile = TTextFile.GetFileEncoding(formletterTemplateFile);
            StreamReader sr          = new StreamReader(formletterTemplateFile, encodingOfHTMLfile, false);
            string       FileContent = sr.ReadToEnd();

            sr.Close();

            string formletterExpectedFile = TAppSettingsManager.GetValue("ReceiptExptected.file",
                                                                         "../../csharp/ICT/Testing/lib/MFinance/SampleData/AnnualReceiptExpected.html");

            Catalog.Init("de-DE", "de-DE");
            sr = new StreamReader(formletterExpectedFile, encodingOfHTMLfile, false);
            string ExpectedFormletterContent = sr.ReadToEnd().
                                               Replace("#TODAY#", DateTime.Now.ToString("d. MMMM yyyy")).
                                               Replace("#THISYEAR#", DateTime.Today.Year.ToString());

            sr.Close();

            StreamWriter sw = new StreamWriter(formletterExpectedFile + ".updated", false, encodingOfHTMLfile);

            sw.WriteLine(ExpectedFormletterContent);
            sw.Close();

            TLanguageCulture.SetLanguageAndCulture("de-DE", "de-DE");

            //TODO: Calendar vs Financial Date Handling - Check if this should use financial year start/end and not assume calendar
            string receipts =
                TReceiptingWebConnector.CreateAnnualGiftReceipts(FLedgerNumber,
                                                                 new DateTime(DateTime.Today.Year, 1, 1), new DateTime(DateTime.Today.Year, 12, 31), FileContent);

            sw = new StreamWriter(formletterExpectedFile + ".new", false, encodingOfHTMLfile);
            sw.WriteLine(receipts);
            sw.WriteLine();
            sw.Close();

            Assert.IsTrue(
                TTextFile.SameContent(formletterExpectedFile + ".updated", formletterExpectedFile + ".new"),
                "receipt was not printed as expected, check " + formletterExpectedFile + ".new");

            File.Delete(formletterExpectedFile + ".new");
            File.Delete(formletterExpectedFile + ".updated");
        }
Esempio n. 25
0
        /// <summary>
        ///
        /// </summary>
        public void SaveChanges()
        {
            DataSet ResponseDS = new PartnerEditTDS();
            TPartnerEditUIConnector       UIConnector = new TPartnerEditUIConnector();
            TVerificationResultCollection VerificationResult;
            TSubmitChangesResult          Result = UIConnector.SubmitChanges(ref MainDS, ref ResponseDS, out VerificationResult);

            CommonNUnitFunctions.EnsureNullOrOnlyNonCriticalVerificationResults(VerificationResult, "There was a critical error when saving:");
        }
Esempio n. 26
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)
        {
            if (File.Exists(AConfigName))
            {
                new TAppSettingsManager(AConfigName);
            }
            else
            {
                new TAppSettingsManager();
            }

            new TLogging(TAppSettingsManager.GetValue("Server.LogFile"));

            CommonNUnitFunctions.InitRootPath();

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

            DBAccess.GDBAccessObj = new TDataBase();
            DBAccess.GDBAccessObj.EstablishDBConnection(TSrvSetting.RDMBSType,
                                                        TSrvSetting.PostgreSQLServer, TSrvSetting.PostgreSQLServerPort,
                                                        TSrvSetting.PostgreSQLDatabaseName,
                                                        TSrvSetting.DBUsername, TSrvSetting.DBPassword, "", "Ict.Testing.NUnitPetraServer.TPetraServerConnector.Connect DB Connection");

            bool       SystemEnabled;
            string     WelcomeMessage;
            IPrincipal ThisUserInfo;
            Int32      ClientID;

            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 ThisUserInfo);

            // the following values are stored in the session object
            DomainManager.GClientID     = ClientID;
            DomainManager.CurrentClient = CurrentClient;
            UserInfo.GUserInfo          = (TPetraPrincipal)ThisUserInfo;

            TSetupDelegates.Init();
            TSystemDefaultsCache.GSystemDefaultsCache = new TSystemDefaultsCache();
            DomainManager.GetSiteKeyFromSystemDefaultsCacheDelegate =
                @TSystemDefaultsCache.GSystemDefaultsCache.GetSiteKeyDefault;

            TUserDefaults.InitializeUnit();

            StringHelper.CurrencyFormatTable = DBAccess.GDBAccessObj.SelectDT("SELECT * FROM PUB_a_currency", "a_currency", null);

            return((TServerManager)TServerManager.TheServerManager);
        }
Esempio n. 27
0
        public void Test_PEMM_05_Revaluation()
        {
            FLedgerNumber = CommonNUnitFunctions.CreateNewLedger();
            // load foreign currency account 6001
            CommonNUnitFunctions.LoadTestDataBase("csharp\\ICT\\Testing\\lib\\MFinance\\GL\\" +
                                                  "test-sql\\gl-test-account-data.sql", FLedgerNumber);

            // post a batch for foreign currency account 6001
            TCommonAccountingTool commonAccountingTool =
                new TCommonAccountingTool(FLedgerNumber, "NUNIT");

            commonAccountingTool.AddForeignCurrencyJournal("GBP", 1.1m);
            commonAccountingTool.JournalDescription = "Test foreign currency account";
            string strAccountGift = "0200";
            string strAccountBank = "6001";

            // Accounting of some gifts ...
            commonAccountingTool.AddBaseCurrencyTransaction(
                strAccountBank, (FLedgerNumber * 100).ToString(), "Gift Example", "Debit", MFinanceConstants.IS_DEBIT, 100);

            commonAccountingTool.AddBaseCurrencyTransaction(
                strAccountGift, (FLedgerNumber * 100).ToString(), "Gift Example", "Credit", MFinanceConstants.IS_CREDIT, 100);

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


            TVerificationResultCollection verificationResult;
            bool blnHasErrors = TPeriodIntervalConnector.TPeriodMonthEnd(
                FLedgerNumber, true, out verificationResult);
            bool blnStatusArrived = false;

            for (int i = 0; i < verificationResult.Count; ++i)
            {
                if (verificationResult[i].ResultCode.Equals(
                        TPeriodEndErrorAndStatusCodes.PEEC_05.ToString()))
                {
                    blnStatusArrived = true;
                    Assert.IsTrue(verificationResult[i].ResultSeverity == TResultSeverity.Resv_Critical,
                                  "we need a critical error: need to run revaluation first ...");
                }
            }

            Assert.IsTrue(blnStatusArrived, "Status message has been shown");
            Assert.IsTrue(blnHasErrors, "should fail because revaluation needs to be run first");

            // run revaluation
            blnHasErrors = TRevaluationWebConnector.Revaluate(FLedgerNumber, new TLedgerInfo(
                                                                  FLedgerNumber).CurrentPeriod, new string[] { "GBP" }, new decimal[] { 1.2m }, out verificationResult);

            TLogging.Log(verificationResult.BuildVerificationResultString());
            Assert.IsFalse(blnHasErrors, "Problem running the revaluation");

            blnHasErrors = TPeriodIntervalConnector.TPeriodMonthEnd(
                FLedgerNumber, true, out verificationResult);
            Assert.IsFalse(blnHasErrors, "should now be able to close the month now that the revaluation has been run");
        }
Esempio n. 28
0
        /// <summary>
        /// prepare the test case
        /// </summary>
        public static bool ImportAndPostGiftBatch(int ALedgerNumber, out TVerificationResultCollection VerificationResult)
        {
            TGiftImporting importer = new TGiftImporting();

            string testFile = TAppSettingsManager.GetValue("GiftBatch.file", "../../csharp/ICT/Testing/lib/MFinance/SampleData/sampleGiftBatch.csv");

            StreamReader sr          = new StreamReader(testFile);
            string       FileContent = sr.ReadToEnd();

            FileContent = FileContent.Replace("{ledgernumber}", ALedgerNumber.ToString());
            FileContent = FileContent.Replace("{thisyear}", DateTime.Today.Year.ToString());

            sr.Close();

            Hashtable parameters = new Hashtable();

            parameters.Add("Delimiter", ",");
            parameters.Add("ALedgerNumber", ALedgerNumber);
            parameters.Add("DateFormatString", "yyyy-MM-dd");
            parameters.Add("DatesMayBeIntegers", false);
            parameters.Add("NumberFormat", "American");
            parameters.Add("NewLine", Environment.NewLine);

            GiftBatchTDSAGiftDetailTable NeedRecipientLedgerNumber;
            bool refreshRequired;

            if (!importer.ImportGiftBatches(parameters, FileContent, out NeedRecipientLedgerNumber, out refreshRequired, out VerificationResult))
            {
                return(false);
            }

            int   BatchNumber = importer.GetLastGiftBatchNumber();
            Int32 generatedGlBatchNumber;

            if (!TGiftTransactionWebConnector.PostGiftBatch(ALedgerNumber, BatchNumber, out generatedGlBatchNumber, out VerificationResult))
            {
                CommonNUnitFunctions.EnsureNullOrOnlyNonCriticalVerificationResults(VerificationResult);

                return(false);
            }

            TDataBase      db           = DBAccess.Connect("FixSendMailPartnerLocation");
            TDBTransaction t            = new TDBTransaction();
            bool           SubmissionOK = false;

            db.WriteTransaction(ref t, ref SubmissionOK,
                                delegate
            {
                // need to set sendmail = true for the donor with partner key 43005001
                string sql = "UPDATE p_partner_location SET p_send_mail_l = true WHERE p_partner_key_n = 43005001";
                db.ExecuteNonQuery(sql, t);
                SubmissionOK = true;
            });

            return(true);
        }
Esempio n. 29
0
        public void Init()
        {
            Catalog.Init();
            new TLogging("../../log/test.log");
            new TAppSettingsManager("../../etc/TestClient.config");
            CommonNUnitFunctions.InitRootPath();

            // just to be sure the server is not running
            CommonNUnitFunctions.nant("stopServer", false);
        }
Esempio n. 30
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)
        {
            if (File.Exists(AConfigName))
            {
                new TAppSettingsManager(AConfigName);
            }
            else
            {
                new TAppSettingsManager();
            }

            new TLogging(TAppSettingsManager.GetValue("Server.LogFile"));

            CommonNUnitFunctions.InitRootPath();

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

            DBAccess.GDBAccessObj = new TDataBase();
            DBAccess.GDBAccessObj.EstablishDBConnection(TSrvSetting.RDMBSType,
                                                        TSrvSetting.PostgreSQLServer, TSrvSetting.PostgreSQLServerPort,
                                                        TSrvSetting.PostgreSQLDatabaseName,
                                                        TSrvSetting.DBUsername, TSrvSetting.DBPassword, "");

            bool            SystemEnabled;
            int             ProcessID;
            TPetraPrincipal UserInfo = (TPetraPrincipal)TClientManager.PerformLoginChecks(TAppSettingsManager.GetValue("AutoLogin").ToUpper(),
                                                                                          TAppSettingsManager.GetValue("AutoLoginPasswd"),
                                                                                          "NUNITTEST", "127.0.0.1", out ProcessID, out SystemEnabled);

            if (FDomain != null)
            {
                FDomain.StopClientAppDomain();
            }

            TClientManager ClientManager = new TClientManager();

            DomainManager.UClientManagerCallForwarderRef = new TClientManagerCallForwarder(ClientManager);

            // do the same as in Ict.Petra.Server.App.Main.TRemoteLoader.LoadDomainManagerAssembly
            FDomain = new TClientDomainManager("0",
                                               TClientServerConnectionType.csctLocal,
                                               DomainManager.UClientManagerCallForwarderRef,
                                               new TSystemDefaultsCache(),
                                               new TCacheableTablesManager(null),
                                               UserInfo);
            FDomain.InitAppDomain(TSrvSetting.ServerSettings);

            new TCallForwarding();

            // we don't need to establish the database connection anymore
            // FDomain.EstablishDBConnection();

            return(ServerManager);
        }