Esempio n. 1
0
        public static Int32 FieldChangeAdjustment(Int32 ALedgerNumber,
                                                  Int64 ARecipientKey,
                                                  DateTime AStartDate,
                                                  DateTime AEndDate,
                                                  Int64 AOldField,
                                                  DateTime ADateCorrection,
                                                  bool AWithReceipt)
        {
            TDBTransaction Transaction = DBAccess.GDBAccessObj.BeginTransaction(IsolationLevel.ReadCommitted);
            GiftBatchTDS   oldGiftDS   = new GiftBatchTDS();

            try
            {
                // find all gifts that need reversing.
                // criteria:
                // posted gift batches only
                // no adjusted/reversed gifts
                // date of gift batch in specified date range
                // recipient field is the old field
                string SqlStmt = TDataBase.ReadSqlFile("Gift.GetGiftsToReverse.sql");

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

                DBAccess.GDBAccessObj.Select(oldGiftDS, SqlStmt, oldGiftDS.AGiftDetail.TableName, Transaction, parameters.ToArray());

                // load the gift and the gift batch records if they have not been loaded yet
                foreach (AGiftDetailRow giftdetail in oldGiftDS.AGiftDetail.Rows)
                {
                    oldGiftDS.AGift.DefaultView.RowFilter = String.Format("{0} = {1} and {2} = {3}",
                                                                          AGiftTable.GetBatchNumberDBName(),
                                                                          giftdetail.BatchNumber,
                                                                          AGiftTable.GetGiftTransactionNumberDBName(),
                                                                          giftdetail.GiftTransactionNumber);

                    if (oldGiftDS.AGift.DefaultView.Count == 0)
                    {
                        AGiftTable tempGiftTable =
                            AGiftAccess.LoadByPrimaryKey(giftdetail.LedgerNumber,
                                                         giftdetail.BatchNumber,
                                                         giftdetail.GiftTransactionNumber,
                                                         Transaction);
                        oldGiftDS.AGift.Merge(tempGiftTable);
                    }

                    oldGiftDS.AGiftBatch.DefaultView.RowFilter = String.Format("{0} = {1}",
                                                                               AGiftTable.GetBatchNumberDBName(),
                                                                               giftdetail.BatchNumber);

                    if (oldGiftDS.AGiftBatch.DefaultView.Count == 0)
                    {
                        AGiftBatchTable tempGiftBatchTable =
                            AGiftBatchAccess.LoadByPrimaryKey(giftdetail.LedgerNumber,
                                                              giftdetail.BatchNumber,
                                                              Transaction);
                        oldGiftDS.AGiftBatch.Merge(tempGiftBatchTable);
                    }
                }

                DBAccess.GDBAccessObj.RollbackTransaction();
            }
            catch (Exception)
            {
                DBAccess.GDBAccessObj.RollbackTransaction();
                throw;
            }

            // we need to create a gift batch for each set of gifts with the same Currency, BankAccountCode, BankCostCentre, and Gift Type
            SortedList <string, GiftBatchTDS> NewGiftBatches = new SortedList <string, GiftBatchTDS>();

            foreach (GiftBatchTDSAGiftDetailRow oldGiftDetail in oldGiftDS.AGiftDetail.Rows)
            {
                // get the gift batch row for this detail
                oldGiftDS.AGiftBatch.DefaultView.RowFilter =
                    String.Format("{0} = {1}",
                                  AGiftTable.GetBatchNumberDBName(), oldGiftDetail.BatchNumber);

                AGiftBatchRow oldGiftBatch = (AGiftBatchRow)oldGiftDS.AGiftBatch.DefaultView[0].Row;

                GiftBatchTDS GiftDS = CreateNewGiftBatch(NewGiftBatches, oldGiftBatch, ADateCorrection);

                AGiftBatchRow giftbatchRow = GiftDS.AGiftBatch[0];

                // get the gift row for this detail
                DataView v = oldGiftDS.AGift.DefaultView;
                v.RowFilter =
                    String.Format("{0} = {1} and {2} = {3}",
                                  AGiftTable.GetBatchNumberDBName(), oldGiftDetail.BatchNumber,
                                  AGiftTable.GetGiftTransactionNumberDBName(), oldGiftDetail.GiftTransactionNumber);

                AGiftRow oldGift = (AGiftRow)v[0].Row;

                AGiftRow gift = GiftDS.AGift.NewRowTyped();
                gift.LedgerNumber          = giftbatchRow.LedgerNumber;
                gift.BatchNumber           = giftbatchRow.BatchNumber;
                gift.GiftTransactionNumber = giftbatchRow.LastGiftNumber + 1;
                gift.DonorKey    = oldGift.DonorKey;
                gift.DateEntered = ADateCorrection;
                giftbatchRow.LastGiftNumber++;
                GiftDS.AGift.Rows.Add(gift);

                if (!AWithReceipt)
                {
                    gift.ReceiptLetterCode = "NO*RECET";
                }

                // reverse the original gift
                GiftBatchTDSAGiftDetailRow detail = GiftDS.AGiftDetail.NewRowTyped();

                DataUtilities.CopyAllColumnValues(oldGiftDetail, detail);

                detail.LedgerNumber          = gift.LedgerNumber;
                detail.BatchNumber           = gift.BatchNumber;
                detail.GiftTransactionNumber = gift.GiftTransactionNumber;
                detail.DetailNumber          = gift.LastDetailNumber + 1;
                detail.GiftAmount            = detail.GiftAmount * -1;
                detail.GiftAmountIntl        = detail.GiftAmountIntl * -1;
                detail.GiftTransactionAmount = detail.GiftTransactionAmount * -1;
                gift.LastDetailNumber++;

                GiftDS.AGiftDetail.Rows.Add(detail);

                // create the detail for the corrected gift to the new field
                detail = GiftDS.AGiftDetail.NewRowTyped();

                DataUtilities.CopyAllColumnValues(oldGiftDetail, detail);

                detail.LedgerNumber          = gift.LedgerNumber;
                detail.BatchNumber           = gift.BatchNumber;
                detail.GiftTransactionNumber = gift.GiftTransactionNumber;
                detail.DetailNumber          = gift.LastDetailNumber + 1;
                detail.GiftCommentOne        = String.Format(Catalog.GetString("posted on {0}"), oldGiftBatch.GlEffectiveDate.ToShortDateString());
                gift.LastDetailNumber++;

                // TODO: calculate costcentre code from current commitment; this currently is done only at time of posting
                // detail.RecipientLedgerNumber = oldGiftDetail.RecipientLedgerNumber;
                // detail.CostCentreCode = oldGiftDetail.CostCentreCode;

                GiftDS.AGiftDetail.Rows.Add(detail);

                // TODO: how to make sure that the gl transaction is marked as System generated? avoid display on HOSA?

                // mark original gift detail as modified
                oldGiftDetail.ModifiedDetail = true;
            }

            TVerificationResultCollection VerificationResult;

            TSubmitChangesResult result = TSubmitChangesResult.scrOK;

            for (Int32 batchCounter = 0; batchCounter < NewGiftBatches.Count; batchCounter++)
            {
                if (result == TSubmitChangesResult.scrOK)
                {
                    GiftBatchTDS GiftDS = NewGiftBatches.Values[batchCounter];
                    result = TGiftTransactionWebConnector.SaveGiftBatchTDS(ref GiftDS, out VerificationResult);
                }
            }

            if (result == TSubmitChangesResult.scrOK)
            {
                result = TGiftTransactionWebConnector.SaveGiftBatchTDS(ref oldGiftDS, out VerificationResult);

                if ((result == TSubmitChangesResult.scrOK) && (NewGiftBatches.Count > 0))
                {
                    return(NewGiftBatches.Values[0].AGiftBatch[0].BatchNumber);
                }
            }

            return(-1);
        }
Esempio n. 2
0
        private static void CheckRecurringTransAnalysisAttributes(ref GLBatchTDS AInspectDS,
            int ALedgerNumber,
            int ABatchNumber,
            int AJournalNumber,
            ref TSubmitChangesResult ASubmissionResult)
        {
            //check if the necessary rows for the given account are there, automatically add/update account
            GLSetupTDS glSetupCacheDS = LoadAAnalysisAttributes(ALedgerNumber);

            //Account Number for AnalysisTable lookup
            int currentTransactionNumber = 0;
            string currentTransAccountCode = String.Empty;

            if (glSetupCacheDS == null)
            {
                return;
            }

            //Reference all transactions in dataset
            DataView allTransView = AInspectDS.ARecurringTransaction.DefaultView;
            DataView transAnalAttrView = AInspectDS.ARecurringTransAnalAttrib.DefaultView;

            transAnalAttrView.RowFilter = string.Empty;

            allTransView.RowFilter = String.Format("{0}={1} and {2}={3}",
                ARecurringTransactionTable.GetBatchNumberDBName(),
                ABatchNumber,
                ARecurringTransactionTable.GetJournalNumberDBName(),
                AJournalNumber);

            foreach (DataRowView transRowView in allTransView)
            {
                ARecurringTransactionRow currentTransactionRow = (ARecurringTransactionRow)transRowView.Row;

                currentTransactionNumber = currentTransactionRow.TransactionNumber;
                currentTransAccountCode = currentTransactionRow.AccountCode;

                //If this account code is used need to delete it from TransAnal table.
                //Delete any existing rows with old code
                transAnalAttrView.RowFilter = String.Format("{0} = {1} AND {2} = {3} AND {4} = {5} AND {6} <> '{7}'",
                    ARecurringTransAnalAttribTable.GetBatchNumberDBName(),
                    ABatchNumber,
                    ARecurringTransAnalAttribTable.GetJournalNumberDBName(),
                    AJournalNumber,
                    ARecurringTransAnalAttribTable.GetTransactionNumberDBName(),
                    currentTransactionNumber,
                    ARecurringTransAnalAttribTable.GetAccountCodeDBName(),
                    currentTransAccountCode);

                foreach (DataRowView dv in transAnalAttrView)
                {
                    ARecurringTransAnalAttribRow tr = (ARecurringTransAnalAttribRow)dv.Row;

                    tr.Delete();
                }

                transAnalAttrView.RowFilter = String.Format("{0}={1} AND {2}={3} AND {4}={5}",
                    ARecurringTransAnalAttribTable.GetBatchNumberDBName(),
                    ABatchNumber,
                    ARecurringTransAnalAttribTable.GetJournalNumberDBName(),
                    AJournalNumber,
                    ARecurringTransAnalAttribTable.GetTransactionNumberDBName(),
                    currentTransactionNumber);

                //Retrieve the analysis attributes for the supplied account
                DataView analAttrView = glSetupCacheDS.AAnalysisAttribute.DefaultView;
                analAttrView.RowFilter = String.Format("{0} = '{1}'",
                    AAnalysisAttributeTable.GetAccountCodeDBName(),
                    currentTransAccountCode);

                if (analAttrView.Count > 0)
                {
                    for (int i = 0; i < analAttrView.Count; i++)
                    {
                        //Read the Type Code for each attribute row
                        AAnalysisAttributeRow analAttrRow = (AAnalysisAttributeRow)analAttrView[i].Row;
                        string analysisTypeCode = analAttrRow.AnalysisTypeCode;

                        //Check if the attribute type code exists in the Transaction Analysis Attributes table
                        ARecurringTransAnalAttribRow transAnalAttrRow =
                            (ARecurringTransAnalAttribRow)AInspectDS.ARecurringTransAnalAttrib.Rows.Find(new object[] { ALedgerNumber, ABatchNumber,
                                                                                                                        AJournalNumber,
                                                                                                                        currentTransactionNumber,
                                                                                                                        analysisTypeCode });

                        if (transAnalAttrRow == null)
                        {
                            //Create a new TypeCode for this account
                            ARecurringTransAnalAttribRow newRow = AInspectDS.ARecurringTransAnalAttrib.NewRowTyped(true);
                            newRow.LedgerNumber = ALedgerNumber;
                            newRow.BatchNumber = ABatchNumber;
                            newRow.JournalNumber = AJournalNumber;
                            newRow.TransactionNumber = currentTransactionNumber;
                            newRow.AnalysisTypeCode = analysisTypeCode;
                            newRow.AccountCode = currentTransAccountCode;

                            AInspectDS.ARecurringTransAnalAttrib.Rows.Add(newRow);
                        }
                        else if (transAnalAttrRow.AccountCode != currentTransAccountCode)
                        {
                            //Check account code is correct
                            transAnalAttrRow.AccountCode = currentTransAccountCode;
                        }
                    }
                }

                GLBatchTDSAccess.SubmitChanges(AInspectDS);

                ASubmissionResult = TSubmitChangesResult.scrOK;

                AInspectDS.ARecurringTransAnalAttrib.AcceptChanges();
            }

            transAnalAttrView.RowFilter = string.Empty;
        }
Esempio n. 3
0
        private static TSubmitChangesResult SaveRecurringGLBatchTDS(ref GLBatchTDS AInspectDS)
        {
            Int32 LedgerNumber;
            Int32 BatchNumber;
            Int32 JournalNumber;
            Int32 TransactionNumber;
            Int32 Counter;

            bool recurrBatchTableInDataSet = (AInspectDS.ARecurringBatch != null);
            bool recurrJournalTableInDataSet = (AInspectDS.ARecurringJournal != null);
            bool recurrTransactionTableInDataSet = (AInspectDS.ARecurringTransaction != null);
            bool recurrTransAnalTableInDataSet = (AInspectDS.ARecurringTransAnalAttrib != null);

            TSubmitChangesResult SubmissionResult = new TSubmitChangesResult();

            ARecurringJournalTable JournalTable = new ARecurringJournalTable();
            ARecurringJournalRow TemplateJournalRow = JournalTable.NewRowTyped(false);

            ARecurringTransactionTable TransactionTable = new ARecurringTransactionTable();
            ARecurringTransactionRow TemplateTransactionRow = TransactionTable.NewRowTyped(false);

            ARecurringTransAnalAttribTable TransAnalAttribTable = new ARecurringTransAnalAttribTable();
            ARecurringTransAnalAttribRow TemplateTransAnalAttribRow = TransAnalAttribTable.NewRowTyped(false);

            GLBatchTDS DeletedDS = new GLBatchTDS();
            ARecurringTransAnalAttribTable DeletedTransAnalAttribTable;

            // in this method we also think about deleted batches, journals, transactions where subsequent information
            // had not been loaded yet: a type of cascading delete is being used (real cascading delete currently does
            // not go down the number of levels needed).

            TDBTransaction Transaction = null;
            GLBatchTDS InspectDS = AInspectDS;

            DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.Serializable,
                ref Transaction,
                delegate
                {
                    if (recurrBatchTableInDataSet)
                    {
                        foreach (ARecurringBatchRow batch in InspectDS.ARecurringBatch.Rows)
                        {
                            if (batch.RowState == DataRowState.Deleted)
                            {
                                // need to use this way of retrieving data from deleted rows
                                LedgerNumber = (Int32)batch[ARecurringBatchTable.ColumnLedgerNumberId, DataRowVersion.Original];
                                BatchNumber = (Int32)batch[ARecurringBatchTable.ColumnBatchNumberId, DataRowVersion.Original];

                                // load all depending journals, transactions and attributes and make sure they are also deleted via the dataset
                                TemplateTransAnalAttribRow.LedgerNumber = LedgerNumber;
                                TemplateTransAnalAttribRow.BatchNumber = BatchNumber;
                                DeletedTransAnalAttribTable =
                                    ARecurringTransAnalAttribAccess.LoadUsingTemplate(TemplateTransAnalAttribRow, Transaction);

                                for (Counter = DeletedTransAnalAttribTable.Count - 1; Counter >= 0; Counter--)
                                {
                                    DeletedTransAnalAttribTable.Rows[Counter].Delete();
                                }

                                InspectDS.Merge(DeletedTransAnalAttribTable);

                                TemplateTransactionRow.LedgerNumber = LedgerNumber;
                                TemplateTransactionRow.BatchNumber = BatchNumber;
                                ARecurringTransactionAccess.LoadUsingTemplate(DeletedDS, TemplateTransactionRow, Transaction);

                                for (Counter = DeletedDS.ARecurringTransaction.Count - 1; Counter >= 0; Counter--)
                                {
                                    DeletedDS.ARecurringTransaction.Rows[Counter].Delete();
                                }

                                InspectDS.Merge(DeletedDS.ARecurringTransaction);

                                TemplateJournalRow.LedgerNumber = LedgerNumber;
                                TemplateJournalRow.BatchNumber = BatchNumber;
                                ARecurringJournalAccess.LoadUsingTemplate(DeletedDS, TemplateJournalRow, Transaction);

                                for (Counter = DeletedDS.ARecurringJournal.Count - 1; Counter >= 0; Counter--)
                                {
                                    DeletedDS.ARecurringJournal.Rows[Counter].Delete();
                                }

                                InspectDS.Merge(DeletedDS.ARecurringJournal);
                            }
                        }
                    }

                    if (recurrJournalTableInDataSet)
                    {
                        foreach (ARecurringJournalRow journal in InspectDS.ARecurringJournal.Rows)
                        {
                            if (journal.RowState == DataRowState.Deleted)
                            {
                                // need to use this way of retrieving data from deleted rows
                                LedgerNumber = (Int32)journal[ARecurringJournalTable.ColumnLedgerNumberId, DataRowVersion.Original];
                                BatchNumber = (Int32)journal[ARecurringJournalTable.ColumnBatchNumberId, DataRowVersion.Original];
                                JournalNumber = (Int32)journal[ARecurringJournalTable.ColumnJournalNumberId, DataRowVersion.Original];

                                // load all depending transactions and attributes and make sure they are also deleted via the dataset
                                TemplateTransAnalAttribRow.LedgerNumber = LedgerNumber;
                                TemplateTransAnalAttribRow.BatchNumber = BatchNumber;
                                TemplateTransAnalAttribRow.JournalNumber = JournalNumber;
                                DeletedTransAnalAttribTable =
                                    ARecurringTransAnalAttribAccess.LoadUsingTemplate(TemplateTransAnalAttribRow, Transaction);

                                for (Counter = DeletedTransAnalAttribTable.Count - 1; Counter >= 0; Counter--)
                                {
                                    DeletedTransAnalAttribTable.Rows[Counter].Delete();
                                }

                                InspectDS.Merge(DeletedTransAnalAttribTable);

                                TemplateTransactionRow.LedgerNumber = LedgerNumber;
                                TemplateTransactionRow.BatchNumber = BatchNumber;
                                TemplateTransactionRow.JournalNumber = JournalNumber;
                                ARecurringTransactionAccess.LoadUsingTemplate(DeletedDS, TemplateTransactionRow, Transaction);

                                for (Counter = DeletedDS.ARecurringTransaction.Count - 1; Counter >= 0; Counter--)
                                {
                                    DeletedDS.ARecurringTransaction.Rows[Counter].Delete();
                                }

                                InspectDS.Merge(DeletedDS.ARecurringTransaction);
                            }
                        }
                    }

                    if (recurrTransactionTableInDataSet)
                    {
                        foreach (ARecurringTransactionRow transaction in InspectDS.ARecurringTransaction.Rows)
                        {
                            if (transaction.RowState == DataRowState.Deleted)
                            {
                                // need to use this way of retrieving data from deleted rows
                                LedgerNumber = (Int32)transaction[ARecurringTransactionTable.ColumnLedgerNumberId, DataRowVersion.Original];
                                BatchNumber = (Int32)transaction[ARecurringTransactionTable.ColumnBatchNumberId, DataRowVersion.Original];
                                JournalNumber = (Int32)transaction[ARecurringTransactionTable.ColumnJournalNumberId, DataRowVersion.Original];
                                TransactionNumber = (Int32)transaction[ARecurringTransactionTable.ColumnTransactionNumberId, DataRowVersion.Original];

                                // load all depending transactions and attributes and make sure they are also deleted via the dataset
                                TemplateTransAnalAttribRow.LedgerNumber = LedgerNumber;
                                TemplateTransAnalAttribRow.BatchNumber = BatchNumber;
                                TemplateTransAnalAttribRow.JournalNumber = JournalNumber;
                                TemplateTransAnalAttribRow.TransactionNumber = TransactionNumber;
                                DeletedTransAnalAttribTable =
                                    ARecurringTransAnalAttribAccess.LoadUsingTemplate(TemplateTransAnalAttribRow, Transaction);

                                for (Counter = DeletedTransAnalAttribTable.Count - 1; Counter >= 0; Counter--)
                                {
                                    DeletedTransAnalAttribTable.Rows[Counter].Delete();
                                }

                                InspectDS.Merge(DeletedTransAnalAttribTable);
                            }
                        }
                    }
                });

            // now submit the changes
            GLBatchTDSAccess.SubmitChanges(AInspectDS);

            SubmissionResult = TSubmitChangesResult.scrOK;

            if (recurrTransactionTableInDataSet)
            {
                //Accept deletion of Attributes to allow deletion of transactions
                if (recurrTransAnalTableInDataSet)
                {
                    AInspectDS.ARecurringTransAnalAttrib.AcceptChanges();
                }

                AInspectDS.ARecurringTransaction.AcceptChanges();

                if (AInspectDS.ARecurringTransaction.Count > 0)
                {
                    ARecurringTransactionRow tranR = (ARecurringTransactionRow)AInspectDS.ARecurringTransaction.Rows[0];

                    Int32 currentLedger = tranR.LedgerNumber;
                    Int32 currentBatch = tranR.BatchNumber;
                    Int32 currentJournal = tranR.JournalNumber;
                    Int32 transToDelete = 0;

                    try
                    {
                        //Check if any records have been marked for deletion
                        DataRow[] foundTransactionForDeletion = AInspectDS.ARecurringTransaction.Select(String.Format("{0} = '{1}'",
                                ARecurringTransactionTable.GetSubTypeDBName(),
                                MFinanceConstants.MARKED_FOR_DELETION));

                        if (foundTransactionForDeletion.Length > 0)
                        {
                            ARecurringTransactionRow transRowClient = null;

                            for (int i = 0; i < foundTransactionForDeletion.Length; i++)
                            {
                                transRowClient = (ARecurringTransactionRow)foundTransactionForDeletion[i];

                                transToDelete = transRowClient.TransactionNumber;
                                TLogging.Log(String.Format("Recurring transaction to Delete: {0} from Journal: {1} in Batch: {2}",
                                        transToDelete,
                                        currentJournal,
                                        currentBatch));

                                transRowClient.Delete();
                            }

                            //save changes
                            GLBatchTDSAccess.SubmitChanges(AInspectDS);

                            SubmissionResult = TSubmitChangesResult.scrOK;
                        }
                    }
                    catch (Exception ex)
                    {
                        TLogging.Log("Saving DataSet: " + ex.Message);

                        TLogging.Log(String.Format("Error trying to save transaction: {0} in Journal: {1}, Batch: {2}",
                                transToDelete,
                                currentJournal,
                                currentBatch
                                ));

                        SubmissionResult = TSubmitChangesResult.scrError;
                    }
                }
            }

            return SubmissionResult;
        }
        public static Int32 CreateGiftBatch(
            Int32 ALedgerNumber,
            Int32 AStatementKey,
            Int32 AGiftBatchNumber,
            out TVerificationResultCollection AVerificationResult)
        {
            BankImportTDS MainDS = GetBankStatementTransactionsAndMatches(AStatementKey, ALedgerNumber);

            string MyClientID = DomainManager.GClientID.ToString();

            TProgressTracker.InitProgressTracker(MyClientID,
                                                 Catalog.GetString("Creating gift batch"),
                                                 MainDS.AEpTransaction.DefaultView.Count + 10);

            AVerificationResult = new TVerificationResultCollection();

            MainDS.AEpTransaction.DefaultView.RowFilter =
                String.Format("{0}={1}",
                              AEpTransactionTable.GetStatementKeyDBName(),
                              AStatementKey);
            MainDS.AEpStatement.DefaultView.RowFilter =
                String.Format("{0}={1}",
                              AEpStatementTable.GetStatementKeyDBName(),
                              AStatementKey);
            AEpStatementRow stmt = (AEpStatementRow)MainDS.AEpStatement.DefaultView[0].Row;

            // TODO: optional: use the preselected gift batch, AGiftBatchNumber

            Int32          DateEffectivePeriodNumber, DateEffectiveYearNumber;
            DateTime       BatchDateEffective = stmt.Date;
            TDBTransaction Transaction        = DBAccess.GDBAccessObj.BeginTransaction(IsolationLevel.ReadCommitted);

            if (!TFinancialYear.GetLedgerDatePostingPeriod(ALedgerNumber, ref BatchDateEffective, out DateEffectiveYearNumber,
                                                           out DateEffectivePeriodNumber,
                                                           Transaction, true))
            {
                // just use the latest possible date
                string msg =
                    String.Format(Catalog.GetString("Date {0} is not in an open period of the ledger, using date {1} instead for the gift batch."),
                                  stmt.Date.ToShortDateString(),
                                  BatchDateEffective.ToShortDateString());
                AVerificationResult.Add(new TVerificationResult(Catalog.GetString("Creating Gift Batch"), msg, TResultSeverity.Resv_Info));
            }

            ACostCentreAccess.LoadViaALedger(MainDS, ALedgerNumber, Transaction);
            AMotivationDetailAccess.LoadViaALedger(MainDS, ALedgerNumber, Transaction);

            MainDS.AEpMatch.DefaultView.Sort =
                AEpMatchTable.GetActionDBName() + ", " +
                AEpMatchTable.GetMatchTextDBName();

            if (MainDS.AEpTransaction.DefaultView.Count == 0)
            {
                AVerificationResult.Add(new TVerificationResult(
                                            Catalog.GetString("Creating Gift Batch"),
                                            String.Format(Catalog.GetString("There are no transactions for statement #{0}."), AStatementKey),
                                            TResultSeverity.Resv_Info));
                return(-1);
            }

            foreach (DataRowView dv in MainDS.AEpTransaction.DefaultView)
            {
                AEpTransactionRow transactionRow = (AEpTransactionRow)dv.Row;

                DataRowView[] matches = MainDS.AEpMatch.DefaultView.FindRows(new object[] {
                    MFinanceConstants.BANK_STMT_STATUS_MATCHED_GIFT,
                    transactionRow.MatchText
                });

                if (matches.Length > 0)
                {
                    AEpMatchRow match = (AEpMatchRow)matches[0].Row;

                    if (match.IsDonorKeyNull() || (match.DonorKey == 0))
                    {
                        string msg =
                            String.Format(Catalog.GetString("Cannot create a gift for transaction {0} since there is no valid donor."),
                                          transactionRow.Description);
                        AVerificationResult.Add(new TVerificationResult(Catalog.GetString("Creating Gift Batch"), msg, TResultSeverity.Resv_Critical));
                        DBAccess.GDBAccessObj.RollbackTransaction();
                        return(-1);
                    }
                }
            }

            string MatchedGiftReference = stmt.Filename;

            if (!stmt.IsBankAccountKeyNull())
            {
                string sqlGetBankSortCode =
                    "SELECT bank.p_branch_code_c " +
                    "FROM PUB_p_banking_details details, PUB_p_bank bank " +
                    "WHERE details.p_banking_details_key_i = ?" +
                    "AND details.p_bank_key_n = bank.p_partner_key_n";
                OdbcParameter param = new OdbcParameter("detailkey", OdbcType.Int);
                param.Value = stmt.BankAccountKey;

                PBankTable bankTable = new PBankTable();
                DBAccess.GDBAccessObj.SelectDT(bankTable, sqlGetBankSortCode, Transaction, new OdbcParameter[] { param }, 0, 0);

                MatchedGiftReference = bankTable[0].BranchCode + " " + stmt.Date.Day.ToString();
            }

            DBAccess.GDBAccessObj.RollbackTransaction();

            GiftBatchTDS GiftDS = TGiftTransactionWebConnector.CreateAGiftBatch(
                ALedgerNumber,
                BatchDateEffective,
                String.Format(Catalog.GetString("bank import for date {0}"), stmt.Date.ToShortDateString()));

            AGiftBatchRow giftbatchRow = GiftDS.AGiftBatch[0];

            giftbatchRow.BankAccountCode = stmt.BankAccountCode;

            decimal HashTotal = 0.0M;

            MainDS.AEpTransaction.DefaultView.Sort =
                AEpTransactionTable.GetNumberOnPaperStatementDBName();

            MainDS.AEpMatch.DefaultView.RowFilter = String.Empty;
            MainDS.AEpMatch.DefaultView.Sort      =
                AEpMatchTable.GetActionDBName() + ", " +
                AEpMatchTable.GetMatchTextDBName();

            int counter = 5;

            foreach (DataRowView dv in MainDS.AEpTransaction.DefaultView)
            {
                TProgressTracker.SetCurrentState(MyClientID,
                                                 Catalog.GetString("Preparing the gifts"),
                                                 counter++);

                AEpTransactionRow transactionRow = (AEpTransactionRow)dv.Row;

                DataRowView[] matches = MainDS.AEpMatch.DefaultView.FindRows(new object[] {
                    MFinanceConstants.BANK_STMT_STATUS_MATCHED_GIFT,
                    transactionRow.MatchText
                });

                if (matches.Length > 0)
                {
                    AEpMatchRow match = (AEpMatchRow)matches[0].Row;

                    AGiftRow gift = GiftDS.AGift.NewRowTyped();
                    gift.LedgerNumber          = giftbatchRow.LedgerNumber;
                    gift.BatchNumber           = giftbatchRow.BatchNumber;
                    gift.GiftTransactionNumber = giftbatchRow.LastGiftNumber + 1;
                    gift.DonorKey    = match.DonorKey;
                    gift.DateEntered = transactionRow.DateEffective;
                    gift.Reference   = MatchedGiftReference;
                    GiftDS.AGift.Rows.Add(gift);
                    giftbatchRow.LastGiftNumber++;

                    foreach (DataRowView r in matches)
                    {
                        match = (AEpMatchRow)r.Row;

                        AGiftDetailRow detail = GiftDS.AGiftDetail.NewRowTyped();
                        detail.LedgerNumber          = gift.LedgerNumber;
                        detail.BatchNumber           = gift.BatchNumber;
                        detail.GiftTransactionNumber = gift.GiftTransactionNumber;
                        detail.DetailNumber          = gift.LastDetailNumber + 1;
                        gift.LastDetailNumber++;

                        detail.GiftTransactionAmount = match.GiftTransactionAmount;
                        detail.GiftAmount            = match.GiftTransactionAmount;
                        HashTotal += match.GiftTransactionAmount;
                        detail.MotivationGroupCode  = match.MotivationGroupCode;
                        detail.MotivationDetailCode = match.MotivationDetailCode;

                        // do not use the description in comment one, because that could show up on the gift receipt???
                        // detail.GiftCommentOne = transactionRow.Description;

                        detail.CommentOneType        = MFinanceConstants.GIFT_COMMENT_TYPE_BOTH;
                        detail.CostCentreCode        = match.CostCentreCode;
                        detail.RecipientKey          = match.RecipientKey;
                        detail.RecipientLedgerNumber = match.RecipientLedgerNumber;

                        AMotivationDetailRow motivation = (AMotivationDetailRow)MainDS.AMotivationDetail.Rows.Find(
                            new object[] { ALedgerNumber, detail.MotivationGroupCode, detail.MotivationDetailCode });

                        if (motivation == null)
                        {
                            AVerificationResult.Add(new TVerificationResult(
                                                        String.Format(Catalog.GetString("creating gift for match {0}"), transactionRow.Description),
                                                        String.Format(Catalog.GetString("Cannot find motivation group '{0}' and motivation detail '{1}'"),
                                                                      detail.MotivationGroupCode, detail.MotivationDetailCode),
                                                        TResultSeverity.Resv_Critical));
                        }

                        if (detail.CostCentreCode.Length == 0)
                        {
                            // try to retrieve the current costcentre for this recipient
                            if (detail.RecipientKey != 0)
                            {
                                detail.RecipientLedgerNumber = TGiftTransactionWebConnector.GetRecipientFundNumber(detail.RecipientKey);

                                detail.CostCentreCode = TGiftTransactionWebConnector.IdentifyPartnerCostCentre(detail.LedgerNumber,
                                                                                                               detail.RecipientLedgerNumber);
                            }
                            else
                            {
                                if (motivation != null)
                                {
                                    detail.CostCentreCode = motivation.CostCentreCode;
                                }
                            }
                        }

                        // check for active cost centre
                        ACostCentreRow costcentre = (ACostCentreRow)MainDS.ACostCentre.Rows.Find(new object[] { ALedgerNumber, detail.CostCentreCode });

                        if ((costcentre == null) || !costcentre.CostCentreActiveFlag)
                        {
                            AVerificationResult.Add(new TVerificationResult(
                                                        String.Format(Catalog.GetString("creating gift for match {0}"), transactionRow.Description),
                                                        Catalog.GetString("Invalid or inactive cost centre"),
                                                        TResultSeverity.Resv_Critical));
                        }

                        GiftDS.AGiftDetail.Rows.Add(detail);
                    }
                }
            }

            TProgressTracker.SetCurrentState(MyClientID,
                                             Catalog.GetString("Submit to database"),
                                             counter++);

            if (AVerificationResult.HasCriticalErrors)
            {
                return(-1);
            }

            giftbatchRow.HashTotal  = HashTotal;
            giftbatchRow.BatchTotal = HashTotal;

            // do not overwrite the parameter, because there might be the hint for a different gift batch date
            TVerificationResultCollection VerificationResultSubmitChanges;

            TSubmitChangesResult result = TGiftTransactionWebConnector.SaveGiftBatchTDS(ref GiftDS,
                                                                                        out VerificationResultSubmitChanges);

            TProgressTracker.FinishJob(MyClientID);

            if (result == TSubmitChangesResult.scrOK)
            {
                return(giftbatchRow.BatchNumber);
            }

            return(-1);
        }
        public static Int32 CreateGLBatch(BankImportTDS AMainDS,
                                          Int32 ALedgerNumber,
                                          Int32 AStatementKey,
                                          Int32 AGLBatchNumber,
                                          out TVerificationResultCollection AVerificationResult)
        {
            AMainDS.AEpTransaction.DefaultView.RowFilter =
                String.Format("{0}={1}",
                              AEpTransactionTable.GetStatementKeyDBName(),
                              AStatementKey);
            AMainDS.AEpStatement.DefaultView.RowFilter =
                String.Format("{0}={1}",
                              AEpStatementTable.GetStatementKeyDBName(),
                              AStatementKey);
            AEpStatementRow stmt = (AEpStatementRow)AMainDS.AEpStatement.DefaultView[0].Row;

            AVerificationResult = null;

            Int32          DateEffectivePeriodNumber, DateEffectiveYearNumber;
            TDBTransaction Transaction = DBAccess.GDBAccessObj.BeginTransaction(IsolationLevel.ReadCommitted);

            if (!TFinancialYear.IsValidPostingPeriod(ALedgerNumber, stmt.Date, out DateEffectivePeriodNumber, out DateEffectiveYearNumber,
                                                     Transaction))
            {
                string msg = String.Format(Catalog.GetString("Cannot create a GL batch for date {0} since it is not in an open period of the ledger."),
                                           stmt.Date.ToShortDateString());
                TLogging.Log(msg);
                AVerificationResult = new TVerificationResultCollection();
                AVerificationResult.Add(new TVerificationResult(Catalog.GetString("Creating GL Batch"), msg, TResultSeverity.Resv_Critical));

                DBAccess.GDBAccessObj.RollbackTransaction();
                return(-1);
            }

            Int32 BatchYear, BatchPeriod;

            // if DateEffective is outside the range of open periods, use the most fitting date
            DateTime DateEffective = stmt.Date;

            TFinancialYear.GetLedgerDatePostingPeriod(ALedgerNumber, ref DateEffective, out BatchYear, out BatchPeriod, Transaction, true);

            ALedgerTable LedgerTable = ALedgerAccess.LoadByPrimaryKey(ALedgerNumber, Transaction);

            DBAccess.GDBAccessObj.RollbackTransaction();

            GLBatchTDS GLDS = TGLTransactionWebConnector.CreateABatch(ALedgerNumber);

            ABatchRow glbatchRow = GLDS.ABatch[0];

            glbatchRow.BatchPeriod      = BatchPeriod;
            glbatchRow.DateEffective    = DateEffective;
            glbatchRow.BatchDescription = String.Format(Catalog.GetString("bank import for date {0}"), stmt.Date.ToShortDateString());

            decimal HashTotal   = 0.0M;
            decimal DebitTotal  = 0.0M;
            decimal CreditTotal = 0.0M;

            // TODO: support several journals
            // TODO: support several currencies, support other currencies than the base currency
            AJournalRow gljournalRow = GLDS.AJournal.NewRowTyped();

            gljournalRow.LedgerNumber        = glbatchRow.LedgerNumber;
            gljournalRow.BatchNumber         = glbatchRow.BatchNumber;
            gljournalRow.JournalNumber       = glbatchRow.LastJournal + 1;
            gljournalRow.TransactionCurrency = LedgerTable[0].BaseCurrency;
            glbatchRow.LastJournal++;
            gljournalRow.JournalPeriod       = glbatchRow.BatchPeriod;
            gljournalRow.DateEffective       = glbatchRow.DateEffective;
            gljournalRow.JournalDescription  = glbatchRow.BatchDescription;
            gljournalRow.SubSystemCode       = CommonAccountingSubSystemsEnum.GL.ToString();
            gljournalRow.TransactionTypeCode = CommonAccountingTransactionTypesEnum.STD.ToString();
            gljournalRow.ExchangeRateToBase  = 1.0m;
            GLDS.AJournal.Rows.Add(gljournalRow);

            foreach (DataRowView dv in AMainDS.AEpTransaction.DefaultView)
            {
                AEpTransactionRow transactionRow = (AEpTransactionRow)dv.Row;

                DataView v = AMainDS.AEpMatch.DefaultView;
                v.RowFilter = AEpMatchTable.GetActionDBName() + " = '" + MFinanceConstants.BANK_STMT_STATUS_MATCHED_GL + "' and " +
                              AEpMatchTable.GetMatchTextDBName() + " = '" + transactionRow.MatchText + "'";

                if (v.Count > 0)
                {
                    AEpMatchRow     match = (AEpMatchRow)v[0].Row;
                    ATransactionRow trans = GLDS.ATransaction.NewRowTyped();
                    trans.LedgerNumber      = glbatchRow.LedgerNumber;
                    trans.BatchNumber       = glbatchRow.BatchNumber;
                    trans.JournalNumber     = gljournalRow.JournalNumber;
                    trans.TransactionNumber = gljournalRow.LastTransactionNumber + 1;
                    trans.AccountCode       = match.AccountCode;
                    trans.CostCentreCode    = match.CostCentreCode;
                    trans.Reference         = match.Reference;
                    trans.Narrative         = match.Narrative;
                    trans.TransactionDate   = transactionRow.DateEffective;

                    if (transactionRow.TransactionAmount < 0)
                    {
                        trans.AmountInBaseCurrency = -1 * transactionRow.TransactionAmount;
                        trans.TransactionAmount    = -1 * transactionRow.TransactionAmount;
                        trans.DebitCreditIndicator = true;
                        DebitTotal += trans.AmountInBaseCurrency;
                    }
                    else
                    {
                        trans.AmountInBaseCurrency = transactionRow.TransactionAmount;
                        trans.TransactionAmount    = transactionRow.TransactionAmount;
                        trans.DebitCreditIndicator = false;
                        CreditTotal += trans.AmountInBaseCurrency;
                    }

                    GLDS.ATransaction.Rows.Add(trans);
                    gljournalRow.LastTransactionNumber++;

                    // add one transaction for the bank as well
                    trans = GLDS.ATransaction.NewRowTyped();
                    trans.LedgerNumber      = glbatchRow.LedgerNumber;
                    trans.BatchNumber       = glbatchRow.BatchNumber;
                    trans.JournalNumber     = gljournalRow.JournalNumber;
                    trans.TransactionNumber = gljournalRow.LastTransactionNumber + 1;
                    trans.AccountCode       = stmt.BankAccountCode;
                    trans.CostCentreCode    = TLedgerInfo.GetStandardCostCentre(ALedgerNumber);
                    trans.Reference         = match.Reference;
                    trans.Narrative         = match.Narrative;
                    trans.TransactionDate   = transactionRow.DateEffective;

                    if (transactionRow.TransactionAmount < 0)
                    {
                        trans.AmountInBaseCurrency = -1 * transactionRow.TransactionAmount;
                        trans.TransactionAmount    = -1 * transactionRow.TransactionAmount;
                        trans.DebitCreditIndicator = false;
                        CreditTotal += trans.AmountInBaseCurrency;
                    }
                    else
                    {
                        trans.AmountInBaseCurrency = transactionRow.TransactionAmount;
                        trans.TransactionAmount    = transactionRow.TransactionAmount;
                        trans.DebitCreditIndicator = true;
                        DebitTotal += trans.AmountInBaseCurrency;
                    }

                    GLDS.ATransaction.Rows.Add(trans);
                    gljournalRow.LastTransactionNumber++;
                }
            }

            gljournalRow.JournalDebitTotal  = DebitTotal;
            gljournalRow.JournalCreditTotal = CreditTotal;
            glbatchRow.BatchDebitTotal      = DebitTotal;
            glbatchRow.BatchCreditTotal     = CreditTotal;
            glbatchRow.BatchControlTotal    = HashTotal;

            TVerificationResultCollection VerificationResult;

            TSubmitChangesResult result = TGLTransactionWebConnector.SaveGLBatchTDS(ref GLDS,
                                                                                    out VerificationResult);

            if (result == TSubmitChangesResult.scrOK)
            {
                return(glbatchRow.BatchNumber);
            }

            TLogging.Log("Problems storing GL Batch");
            return(-1);
        }
Esempio n. 6
0
        public static TSubmitChangesResult SaveSUser(ref MaintainUsersTDS ASubmitDS)
        {
            TSubmitChangesResult ReturnValue = TSubmitChangesResult.scrError;

            bool CanCreateUser;
            bool CanChangePassword;
            bool CanChangePermissions;

            GetAuthenticationFunctionality(out CanCreateUser, out CanChangePassword, out CanChangePermissions);

            // make sure users are not deleted or added if this is not possible
            if (!CanCreateUser && (ASubmitDS.SUser != null))
            {
                Int32 Counter = 0;

                while (Counter < ASubmitDS.SUser.Rows.Count)
                {
                    if (ASubmitDS.SUser.Rows[Counter].RowState != DataRowState.Modified)
                    {
                        ASubmitDS.SUser.Rows.RemoveAt(Counter);
                    }
                    else
                    {
                        Counter++;
                    }
                }
            }

            if (!CanChangePermissions && (ASubmitDS.SUserModuleAccessPermission != null))
            {
                ASubmitDS.SUserModuleAccessPermission.Clear();
            }

            // TODO: if user module access permissions have changed, automatically update the table access permissions?

            if (ASubmitDS.SUser != null)
            {
                foreach (SUserRow user in ASubmitDS.SUser.Rows)
                {
                    // for new users: create users on the alternative authentication method
                    if (user.RowState == DataRowState.Added)
                    {
                        CreateUser(user.UserId, user.PasswordHash, user.FirstName, user.LastName, string.Empty);
                        user.AcceptChanges();
                    }
                    // If a password has been added for the first time there will be a (unecrypted) password and no salt.
                    // Create salt and hash.
                    else if ((user.PasswordHash.Length > 0) && user.IsPasswordSaltNull())
                    {
                        user.PasswordSalt        = PasswordHelper.GetNewPasswordSalt();
                        user.PasswordHash        = PasswordHelper.GetPasswordHash(user.PasswordHash, user.PasswordSalt);
                        user.PasswordNeedsChange = true;
                    }
                }
            }

            try
            {
                MaintainUsersTDSAccess.SubmitChanges(ASubmitDS);

                ReturnValue = TSubmitChangesResult.scrOK;
            }
            catch (Exception e)
            {
                TLogging.Log(e.Message);
                TLogging.Log(e.StackTrace);
                ReturnValue = TSubmitChangesResult.scrError;
            }

            return(ReturnValue);
        }
        public void TestBankingDetails()
        {
            TPartnerEditUIConnector connector = new TPartnerEditUIConnector();

            PartnerEditTDS MainDS = new PartnerEditTDS();

            PPartnerRow PartnerRow = TCreateTestPartnerData.CreateNewFamilyPartner(MainDS);

            TCreateTestPartnerData.CreateNewLocation(PartnerRow.PartnerKey, MainDS);

            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, "TPartnerEditUIConnector SubmitChanges return value");

            connector = new TPartnerEditUIConnector(PartnerRow.PartnerKey);

            // add a banking detail
            PartnerEditTDSPBankingDetailsRow bankingDetailsRow = MainDS.PBankingDetails.NewRowTyped(true);

            bankingDetailsRow.AccountName       = "account of " + PartnerRow.PartnerShortName;
            bankingDetailsRow.BankAccountNumber = new Random().Next().ToString();
            bankingDetailsRow.BankingDetailsKey = (MainDS.PBankingDetails.Count + 1) * -1;
            bankingDetailsRow.BankKey           = 43005004;
            bankingDetailsRow.MainAccount       = true;
            bankingDetailsRow.BankingType       = MPartnerConstants.BANKINGTYPE_BANKACCOUNT;
            MainDS.PBankingDetails.Rows.Add(bankingDetailsRow);

            PPartnerBankingDetailsRow partnerBankingDetails = MainDS.PPartnerBankingDetails.NewRowTyped(true);

            partnerBankingDetails.PartnerKey        = PartnerRow.PartnerKey;
            partnerBankingDetails.BankingDetailsKey = bankingDetailsRow.BankingDetailsKey;
            MainDS.PPartnerBankingDetails.Rows.Add(partnerBankingDetails);

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

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

            foreach (DataTable t in MainDS.Tables)
            {
                if ((t == MainDS.PBankingDetails) ||
                    (t == MainDS.PPartnerBankingDetails) ||
                    (t == MainDS.PDataLabelValuePartner))
                {
                    int NumRows = t.Rows.Count;

                    for (int RowIndex = NumRows - 1; RowIndex >= 0; RowIndex -= 1)
                    {
                        DataRow InspectDR = t.Rows[RowIndex];

                        // delete all added Rows.
                        if (InspectDR.RowState == DataRowState.Added)
                        {
                            InspectDR.Delete();
                        }
                    }
                }
            }

            MainDS.AcceptChanges();

            Assert.AreEqual(1, PBankingDetailsUsageAccess.CountViaPPartner(PartnerRow.PartnerKey, null), "count of main accounts for partner");

            // add another account
            bankingDetailsRow                   = MainDS.PBankingDetails.NewRowTyped(true);
            bankingDetailsRow.AccountName       = "2nd account of " + PartnerRow.PartnerShortName;
            bankingDetailsRow.BankAccountNumber = new Random().Next().ToString();
            bankingDetailsRow.BankingDetailsKey = (MainDS.PBankingDetails.Count + 1) * -1;
            bankingDetailsRow.BankKey           = 43005004;
            bankingDetailsRow.MainAccount       = false;
            bankingDetailsRow.BankingType       = MPartnerConstants.BANKINGTYPE_BANKACCOUNT;
            MainDS.PBankingDetails.Rows.Add(bankingDetailsRow);

            partnerBankingDetails                   = MainDS.PPartnerBankingDetails.NewRowTyped(true);
            partnerBankingDetails.PartnerKey        = PartnerRow.PartnerKey;
            partnerBankingDetails.BankingDetailsKey = bankingDetailsRow.BankingDetailsKey;
            MainDS.PPartnerBankingDetails.Rows.Add(partnerBankingDetails);

            PartnerEditTDS ChangedDS = MainDS.GetChangesTyped(true);

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

            foreach (DataTable t in MainDS.Tables)
            {
                if ((t == MainDS.PBankingDetails) ||
                    (t == MainDS.PPartnerBankingDetails) ||
                    (t == MainDS.PDataLabelValuePartner))
                {
                    int NumRows = t.Rows.Count;

                    for (int RowIndex = NumRows - 1; RowIndex >= 0; RowIndex -= 1)
                    {
                        DataRow InspectDR = t.Rows[RowIndex];

                        // delete all added Rows.
                        if (InspectDR.RowState == DataRowState.Added)
                        {
                            InspectDR.Delete();
                        }
                    }
                }
            }

            MainDS.AcceptChanges();

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

            // now delete the main bank account
            PartnerEditTDSPBankingDetailsRow toDelete = null;

            foreach (PartnerEditTDSPBankingDetailsRow row in MainDS.PBankingDetails.Rows)
            {
                if (row.MainAccount)
                {
                    toDelete = row;
                    break;
                }
            }

            Assert.IsNotNull(toDelete, "cannot find main account");
            Assert.AreEqual(true, toDelete.MainAccount, "should be the main account");
            MainDS.PPartnerBankingDetails.Rows.Find(new object[] { PartnerRow.PartnerKey, toDelete.BankingDetailsKey }).Delete();
            toDelete.Delete();

            ChangedDS = MainDS.GetChangesTyped(true);
            result    = connector.SubmitChanges(ref ChangedDS, ref ResponseDS, out VerificationResult);

            Assert.AreEqual(1, VerificationResult.Count, "should fail because we have no main account anymore");
            Assert.AreEqual(
                "One Bank Account of a Partner must be set as the 'Main Account'. Please select the record that should become the 'Main Account' and choose 'Set Main Account'.",
                VerificationResult[0].ResultText,
                "should fail because we have no main account anymore");

            PartnerEditTDSPBankingDetailsRow otherAccount = null;

            foreach (PartnerEditTDSPBankingDetailsRow row in MainDS.PBankingDetails.Rows)
            {
                if ((row.RowState != DataRowState.Deleted) && !row.MainAccount)
                {
                    otherAccount = row;
                    break;
                }
            }

            otherAccount.MainAccount = true;

            ChangedDS = MainDS.GetChangesTyped(true);
            result    = connector.SubmitChanges(ref ChangedDS, ref ResponseDS, out VerificationResult);

            MainDS.Merge(ChangedDS);
            MainDS.AcceptChanges();

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

            // now delete the last remaining bank account
            toDelete = MainDS.PBankingDetails[0];
            Assert.AreEqual(true, toDelete.MainAccount);
            MainDS.PPartnerBankingDetails.Rows.Find(new object[] { PartnerRow.PartnerKey, toDelete.BankingDetailsKey }).Delete();
            toDelete.Delete();
            ChangedDS = MainDS.GetChangesTyped(true);
            result    = connector.SubmitChanges(ref ChangedDS, ref ResponseDS, out VerificationResult);
            MainDS.Merge(ChangedDS);
            MainDS.AcceptChanges();

            CommonNUnitFunctions.EnsureNullOrOnlyNonCriticalVerificationResults(VerificationResult,
                                                                                "There was a critical error when saving 5:");
        }
Esempio n. 8
0
        public void TestNewPartnerWithLocation0()
        {
            TPartnerEditUIConnector connector = new TPartnerEditUIConnector();

            PartnerEditTDS MainDS = new PartnerEditTDS();

            PPartnerRow PartnerRow = TCreateTestPartnerData.CreateNewFamilyPartner(MainDS);

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

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

            // get all addresses of the partner
            TDBTransaction ReadTransaction = null;

            DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted, TEnforceIsolationLevel.eilMinimum,
                                                                      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");
            });
        }
Esempio n. 9
0
        public static bool SavePartner(PartnerEditTDS AMainDS,
                                       List <string> ASubscriptions,
                                       List <string> APartnerTypes,
                                       bool ASendMail,
                                       string ADefaultEmailAddress,
                                       string ADefaultPhoneMobile,
                                       string ADefaultPhoneLandline,
                                       out TVerificationResultCollection AVerificationResult)
        {
            List <string>  Dummy1, Dummy2;
            string         Dummy3, Dummy4, Dummy5;
            PartnerEditTDS SaveDS;

            AVerificationResult = new TVerificationResultCollection();

            if (AMainDS.PPartner[0].ModificationId == DateTime.MinValue)
            {
                // this is a new partner
                SaveDS = AMainDS;

                if (SaveDS.PPartner[0].PartnerKey == -1)
                {
                    SaveDS.PPartner[0].PartnerKey = NewPartnerKey();
                }

                if (SaveDS.PFamily.Count > 0)
                {
                    SaveDS.PFamily[0].PartnerKey = SaveDS.PPartner[0].PartnerKey;
                }
                else if (SaveDS.PPerson.Count > 0)
                {
                    SaveDS.PPerson[0].PartnerKey = SaveDS.PPartner[0].PartnerKey;
                }
                else if (SaveDS.PChurch.Count > 0)
                {
                    SaveDS.PChurch[0].PartnerKey = SaveDS.PPartner[0].PartnerKey;
                }
                else if (SaveDS.POrganisation.Count > 0)
                {
                    SaveDS.POrganisation[0].PartnerKey = SaveDS.PPartner[0].PartnerKey;
                }

                PPartnerLocationRow partnerlocation = SaveDS.PPartnerLocation.NewRowTyped();
                partnerlocation.PartnerKey  = SaveDS.PPartner[0].PartnerKey;
                partnerlocation.LocationKey = SaveDS.PLocation[0].LocationKey;
                partnerlocation.SiteKey     = SaveDS.PLocation[0].SiteKey;
                partnerlocation.SendMail    = ASendMail;
                SaveDS.PPartnerLocation.Rows.Add(partnerlocation);
            }
            else
            {
                SaveDS = GetPartnerDetails(AMainDS.PPartner[0].PartnerKey, out Dummy1, out Dummy2, out Dummy3, out Dummy4, out Dummy5);
                DataUtilities.CopyDataSet(AMainDS, SaveDS);
            }

            List <string> ExistingPartnerTypes = new List <string>();

            foreach (PPartnerTypeRow partnertype in SaveDS.PPartnerType.Rows)
            {
                if (!APartnerTypes.Contains(partnertype.TypeCode))
                {
                    partnertype.Delete();
                }
                else
                {
                    ExistingPartnerTypes.Add(partnertype.TypeCode);
                }
            }

            // add new partner types
            foreach (string partnertype in APartnerTypes)
            {
                if (!ExistingPartnerTypes.Contains(partnertype))
                {
                    PPartnerTypeRow partnertypeRow = SaveDS.PPartnerType.NewRowTyped();
                    partnertypeRow.PartnerKey = AMainDS.PPartner[0].PartnerKey;
                    partnertypeRow.TypeCode   = partnertype;
                    SaveDS.PPartnerType.Rows.Add(partnertypeRow);
                }
            }

            List <string> ExistingSubscriptions = new List <string>();

            foreach (PSubscriptionRow subscription in SaveDS.PSubscription.Rows)
            {
                if (!ASubscriptions.Contains(subscription.PublicationCode))
                {
                    subscription.Delete();
                }
                else
                {
                    ExistingSubscriptions.Add(subscription.PublicationCode);
                }
            }

            // add new subscriptions
            foreach (string subscription in ASubscriptions)
            {
                if (!ExistingSubscriptions.Contains(subscription))
                {
                    PSubscriptionRow subscriptionRow = SaveDS.PSubscription.NewRowTyped();
                    subscriptionRow.PartnerKey          = AMainDS.PPartner[0].PartnerKey;
                    subscriptionRow.PublicationCode     = subscription;
                    subscriptionRow.ReasonSubsGivenCode = "FREE";
                    SaveDS.PSubscription.Rows.Add(subscriptionRow);
                }
            }

            bool foundDefaultEmailAddress   = false;
            bool foundDefaultPhoneLandLine  = false;
            bool foundDefaultMobileLandLine = false;

            foreach (PPartnerAttributeRow partnerattr in SaveDS.PPartnerAttribute.Rows)
            {
                if (partnerattr.AttributeType == MPartnerConstants.ATTR_TYPE_EMAIL)
                {
                    partnerattr.Value        = ADefaultEmailAddress;
                    foundDefaultEmailAddress = true;
                }
                else if (partnerattr.AttributeType == MPartnerConstants.ATTR_TYPE_PHONE)
                {
                    partnerattr.Value         = ADefaultPhoneLandline;
                    foundDefaultPhoneLandLine = true;
                }
                else if (partnerattr.AttributeType == MPartnerConstants.ATTR_TYPE_MOBILE_PHONE)
                {
                    partnerattr.Value          = ADefaultPhoneMobile;
                    foundDefaultMobileLandLine = true;
                }
            }

            if (!foundDefaultEmailAddress)
            {
                PPartnerAttributeRow partnerattr = SaveDS.PPartnerAttribute.NewRowTyped();
                partnerattr.PartnerKey    = SaveDS.PPartner[0].PartnerKey;
                partnerattr.AttributeType = MPartnerConstants.ATTR_TYPE_EMAIL;
                partnerattr.Value         = ADefaultEmailAddress;
                SaveDS.PPartnerAttribute.Rows.Add(partnerattr);
            }

            if (!foundDefaultPhoneLandLine)
            {
                PPartnerAttributeRow partnerattr = SaveDS.PPartnerAttribute.NewRowTyped();
                partnerattr.PartnerKey    = SaveDS.PPartner[0].PartnerKey;
                partnerattr.AttributeType = MPartnerConstants.ATTR_TYPE_PHONE;
                partnerattr.Value         = ADefaultPhoneLandline;
                SaveDS.PPartnerAttribute.Rows.Add(partnerattr);
            }

            if (!foundDefaultMobileLandLine)
            {
                PPartnerAttributeRow partnerattr = SaveDS.PPartnerAttribute.NewRowTyped();
                partnerattr.PartnerKey    = SaveDS.PPartner[0].PartnerKey;
                partnerattr.AttributeType = MPartnerConstants.ATTR_TYPE_MOBILE_PHONE;
                partnerattr.Value         = ADefaultPhoneMobile;
                SaveDS.PPartnerAttribute.Rows.Add(partnerattr);
            }

            // TODO: either reuse Partner Edit UIConnector
            // or check for changed partner key, or changed Partner Class, etc.

            // set Partner Short Name
            if (SaveDS.PPartner[0].PartnerClass == MPartnerConstants.PARTNERCLASS_PERSON)
            {
                SaveDS.PPartner[0].PartnerShortName =
                    Calculations.DeterminePartnerShortName(
                        SaveDS.PPerson[0].FamilyName,
                        SaveDS.PPerson[0].Title,
                        SaveDS.PPerson[0].FirstName,
                        SaveDS.PPerson[0].MiddleName1);
            }
            else if (SaveDS.PPartner[0].PartnerClass == MPartnerConstants.PARTNERCLASS_FAMILY)
            {
                SaveDS.PPartner[0].PartnerShortName =
                    Calculations.DeterminePartnerShortName(
                        SaveDS.PFamily[0].FamilyName,
                        SaveDS.PFamily[0].Title,
                        SaveDS.PFamily[0].FirstName);
            }
            else if (SaveDS.PPartner[0].PartnerClass == MPartnerConstants.PARTNERCLASS_UNIT)
            {
                SaveDS.PPartner[0].PartnerShortName = SaveDS.PUnit[0].UnitName;
            }
            else if (SaveDS.PPartner[0].PartnerClass == MPartnerConstants.PARTNERCLASS_ORGANISATION)
            {
                SaveDS.PPartner[0].PartnerShortName = SaveDS.POrganisation[0].OrganisationName;
            }
            else if (SaveDS.PPartner[0].PartnerClass == MPartnerConstants.PARTNERCLASS_BANK)
            {
                SaveDS.PPartner[0].PartnerShortName = SaveDS.PBank[0].BranchName;
            }

            // TODO: check if location 0 (no address) was changed. we don't want to overwrite that
            // alternative: check if somebody else uses that location, and split the locations. or ask if others should be updated???
            if (SaveDS.PLocation[0].RowState == DataRowState.Modified && SaveDS.PLocation[0].LocationKey == 0)
            {
                TLogging.Log("we cannot update addresses of people with location 0");
                AVerificationResult.Add(new TVerificationResult("error", "we cannot update addresses of people with location 0", TResultSeverity.Resv_Critical));
                return(false);
            }

            DataSet ResponseDS = new PartnerEditTDS();
            TPartnerEditUIConnector uiconnector = new TPartnerEditUIConnector(SaveDS.PPartner[0].PartnerKey);

            try
            {
                TSubmitChangesResult result = uiconnector.SubmitChanges(
                    ref SaveDS,
                    ref ResponseDS,
                    out AVerificationResult);
                return(result == TSubmitChangesResult.scrOK);
            }
            catch (Exception e)
            {
                TLogging.Log(e.ToString());
                AVerificationResult.Add(new TVerificationResult("error", e.Message, TResultSeverity.Resv_Critical));
                return(false);
            }
        }
Esempio n. 10
0
        public static TSubmitChangesResult SaveSUser(ref MaintainUsersTDS ASubmitDS,
                                                     string AClientComputerName, string AClientIPAddress)
        {
            TSubmitChangesResult ReturnValue = TSubmitChangesResult.scrError;
            TDBTransaction       SubmitChangesTransaction = null;
            bool             CanCreateUser;
            bool             CanChangePassword;
            bool             CanChangePermissions;
            int              PwdSchemeVersionUpTillNow;
            int              CurrentPwdSchemeVersion = TPasswordHelper.CurrentPasswordSchemeNumber;
            MaintainUsersTDS SubmitDS;

            SubmitDS = ASubmitDS;

            GetAuthenticationFunctionality(out CanCreateUser, out CanChangePassword, out CanChangePermissions);

            // make sure users are not deleted or added if this is not possible
            if (!CanCreateUser && (ASubmitDS.SUser != null))
            {
                Int32 Counter = 0;

                while (Counter < ASubmitDS.SUser.Rows.Count)
                {
                    if (ASubmitDS.SUser.Rows[Counter].RowState != DataRowState.Modified)
                    {
                        ASubmitDS.SUser.Rows.RemoveAt(Counter);
                    }
                    else
                    {
                        Counter++;
                    }
                }
            }

            if (!CanChangePermissions && (ASubmitDS.SUserModuleAccessPermission != null))
            {
                ASubmitDS.SUserModuleAccessPermission.Clear();
            }

            // TODO: if user module access permissions have changed, automatically update the table access permissions?

            DBAccess.SimpleAutoTransactionWrapper(IsolationLevel.Serializable, "SaveSUser", out SubmitChangesTransaction,
                                                  ref ReturnValue, delegate
            {
                if (SubmitDS.SUser != null)
                {
                    foreach (SUserRow user in SubmitDS.SUser.Rows)
                    {
                        // for new users: create users on the alternative authentication method
                        if (user.RowState == DataRowState.Added)
                        {
                            CreateUser(user.UserId, user.PasswordHash, user.FirstName, user.LastName, string.Empty,
                                       AClientComputerName, AClientIPAddress, SubmitChangesTransaction);
                            user.AcceptChanges();
                        }
                        else
                        {
                            PwdSchemeVersionUpTillNow = user.PwdSchemeVersion;

                            // Has the 'Account Locked' state changed?
                            if (Convert.ToBoolean(user[SUserTable.GetAccountLockedDBName(), DataRowVersion.Original]) != user.AccountLocked)
                            {
                                if (user.AccountLocked)
                                {
                                    TUserAccountActivityLog.AddUserAccountActivityLogEntry(user.UserId,
                                                                                           TUserAccountActivityLog.USER_ACTIVITY_USER_ACCOUNT_GOT_LOCKED,
                                                                                           String.Format(
                                                                                               StrUserChangedOtherUsersLockedState, UserInfo.GUserInfo.UserID,
                                                                                               user.UserId, Catalog.GetString("locked")) +
                                                                                           String.Format(ResourceTexts.StrRequestCallerInfo, AClientComputerName, AClientIPAddress),
                                                                                           SubmitChangesTransaction);
                                }
                                else
                                {
                                    TUserAccountActivityLog.AddUserAccountActivityLogEntry(user.UserId,
                                                                                           TUserAccountActivityLog.USER_ACTIVITY_USER_ACCOUNT_GOT_UNLOCKED,
                                                                                           String.Format(
                                                                                               StrUserChangedOtherUsersLockedState, UserInfo.GUserInfo.UserID,
                                                                                               user.UserId, Catalog.GetString("unlocked")) +
                                                                                           String.Format(ResourceTexts.StrRequestCallerInfo, AClientComputerName, AClientIPAddress),
                                                                                           SubmitChangesTransaction);

                                    // If the user account got locked when a Password Hashing Scheme was in place that isn't
                                    // the current one then require the user to change his/her password on next login. This is to
                                    // ensure that the Password Hash and Salt that gets placed in the s_user table record of this
                                    // user at his/her next logon isn't just the new Password Hash and Salt of the password that
                                    // the user had used when the user account got Locked (the Password Hashing Scheme of that user
                                    // will get upgraded to the current one then, but in case the system administrator locked the user
                                    // account because (s)he suspects a security breach then any future attempts to use the previous
                                    // password will be thwarted).
                                    if (PwdSchemeVersionUpTillNow != CurrentPwdSchemeVersion)
                                    {
                                        user.PasswordNeedsChange = true;
                                    }
                                }
                            }

                            // Has the 'Retired' state changed?
                            if (Convert.ToBoolean(user[SUserTable.GetRetiredDBName(), DataRowVersion.Original]) != user.Retired)
                            {
                                if (user.Retired)
                                {
                                    TUserAccountActivityLog.AddUserAccountActivityLogEntry(user.UserId,
                                                                                           TUserAccountActivityLog.USER_ACTIVITY_USER_GOT_RETIRED,
                                                                                           String.Format(
                                                                                               StrUserChangedOtherUsersRetiredState, UserInfo.GUserInfo.UserID,
                                                                                               user.UserId, Catalog.GetString("retired")) +
                                                                                           String.Format(ResourceTexts.StrRequestCallerInfo, AClientComputerName, AClientIPAddress),
                                                                                           SubmitChangesTransaction);
                                }
                                else
                                {
                                    TUserAccountActivityLog.AddUserAccountActivityLogEntry(user.UserId,
                                                                                           TUserAccountActivityLog.USER_ACTIVITY_USER_GOT_UNRETIRED,
                                                                                           String.Format(
                                                                                               StrUserChangedOtherUsersRetiredState, UserInfo.GUserInfo.UserID,
                                                                                               user.UserId, Catalog.GetString("no longer retired")) +
                                                                                           String.Format(ResourceTexts.StrRequestCallerInfo, AClientComputerName, AClientIPAddress),
                                                                                           SubmitChangesTransaction);

                                    // If the user account got retired when a Password Hashing Scheme was in place that isn't
                                    // the current one then require the user to change his/her password on next login. This is to
                                    // ensure that the Password Hash and Salt that gets placed in the s_user table record of this
                                    // user at his/her next logon isn't just the new Password Hash and Salt of the password that
                                    // the user had used when the user account got Retired (the Password Hashing Scheme of that user
                                    // will get upgraded to the current one then, but in case the system administrator retired the user
                                    // account because (s)he suspects a security breach then any future attempts to use the previous
                                    // password will be thwarted).
                                    if (PwdSchemeVersionUpTillNow != CurrentPwdSchemeVersion)
                                    {
                                        user.PasswordNeedsChange = true;
                                    }
                                }
                            }
                        }
                    }
                }

                try
                {
                    MaintainUsersTDSAccess.SubmitChanges(SubmitDS, SubmitChangesTransaction.DataBaseObj);

                    ReturnValue = TSubmitChangesResult.scrOK;
                }
                catch (Exception e)
                {
                    TLogging.Log(e.Message);
                    TLogging.Log(e.StackTrace);

                    throw;
                }
            });

            ASubmitDS = SubmitDS;

            return(ReturnValue);
        }
Esempio n. 11
0
        public static bool SavePartner(PartnerEditTDS AMainDS,
                                       List <string> ASubscriptions,
                                       List <string> APartnerTypes,
                                       bool ASendMail,
                                       string ADefaultEmailAddress,
                                       string ADefaultPhoneMobile,
                                       string ADefaultPhoneLandline,
                                       out TVerificationResultCollection AVerificationResult)
        {
            List <string>  Dummy1, Dummy2;
            string         Dummy3, Dummy4, Dummy5;
            PartnerEditTDS SaveDS;

            AVerificationResult = new TVerificationResultCollection();

            if (AMainDS.PPartner[0].ModificationId == DateTime.MinValue)
            {
                // this is a new partner
                SaveDS = AMainDS;

                if (SaveDS.PPartner[0].PartnerKey == -1)
                {
                    SaveDS.PPartner[0].PartnerKey = NewPartnerKey();
                }

                if (SaveDS.PFamily.Count > 0)
                {
                    SaveDS.PFamily[0].PartnerKey = SaveDS.PPartner[0].PartnerKey;
                }
                else if (SaveDS.PPerson.Count > 0)
                {
                    SaveDS.PPerson[0].PartnerKey = SaveDS.PPartner[0].PartnerKey;
                }
                else if (SaveDS.PChurch.Count > 0)
                {
                    SaveDS.PChurch[0].PartnerKey = SaveDS.PPartner[0].PartnerKey;
                }
                else if (SaveDS.POrganisation.Count > 0)
                {
                    SaveDS.POrganisation[0].PartnerKey = SaveDS.PPartner[0].PartnerKey;
                }

                PPartnerLocationRow partnerlocation = SaveDS.PPartnerLocation.NewRowTyped();
                partnerlocation.PartnerKey  = SaveDS.PPartner[0].PartnerKey;
                partnerlocation.LocationKey = SaveDS.PLocation[0].LocationKey;
                partnerlocation.SiteKey     = SaveDS.PLocation[0].SiteKey;
                partnerlocation.SendMail    = ASendMail;
                SaveDS.PPartnerLocation.Rows.Add(partnerlocation);
            }
            else
            {
                SaveDS = GetPartnerDetails(AMainDS.PPartner[0].PartnerKey, out Dummy1, out Dummy2, out Dummy3, out Dummy4, out Dummy5);
                DataUtilities.CopyDataSet(AMainDS, SaveDS);
            }

            List <string> ExistingPartnerTypes = new List <string>();

            foreach (PPartnerTypeRow partnertype in SaveDS.PPartnerType.Rows)
            {
                if (!APartnerTypes.Contains(partnertype.TypeCode))
                {
                    partnertype.Delete();
                }
                else
                {
                    ExistingPartnerTypes.Add(partnertype.TypeCode);
                }
            }

            // add new partner types
            foreach (string partnertype in APartnerTypes)
            {
                if (!ExistingPartnerTypes.Contains(partnertype))
                {
                    PPartnerTypeRow partnertypeRow = SaveDS.PPartnerType.NewRowTyped();
                    partnertypeRow.PartnerKey = AMainDS.PPartner[0].PartnerKey;
                    partnertypeRow.TypeCode   = partnertype;
                    SaveDS.PPartnerType.Rows.Add(partnertypeRow);
                }
            }

            List <string> ExistingSubscriptions = new List <string>();

            foreach (PSubscriptionRow subscription in SaveDS.PSubscription.Rows)
            {
                if (!ASubscriptions.Contains(subscription.PublicationCode))
                {
                    subscription.Delete();
                }
                else
                {
                    ExistingSubscriptions.Add(subscription.PublicationCode);
                }
            }

            // add new subscriptions
            foreach (string subscription in ASubscriptions)
            {
                if (!ExistingSubscriptions.Contains(subscription))
                {
                    PSubscriptionRow subscriptionRow = SaveDS.PSubscription.NewRowTyped();
                    subscriptionRow.PartnerKey          = AMainDS.PPartner[0].PartnerKey;
                    subscriptionRow.PublicationCode     = subscription;
                    subscriptionRow.ReasonSubsGivenCode = "FREE";
                    SaveDS.PSubscription.Rows.Add(subscriptionRow);
                }
            }

            bool foundDefaultEmailAddress   = false;
            bool foundDefaultPhoneLandLine  = false;
            bool foundDefaultMobileLandLine = false;

            foreach (PPartnerAttributeRow partnerattr in SaveDS.PPartnerAttribute.Rows)
            {
                if (partnerattr.AttributeType == MPartnerConstants.ATTR_TYPE_EMAIL)
                {
                    partnerattr.Value        = ADefaultEmailAddress;
                    foundDefaultEmailAddress = true;
                }
                else if (partnerattr.AttributeType == MPartnerConstants.ATTR_TYPE_PHONE)
                {
                    partnerattr.Value         = ADefaultPhoneLandline;
                    foundDefaultPhoneLandLine = true;
                }
                else if (partnerattr.AttributeType == MPartnerConstants.ATTR_TYPE_MOBILE_PHONE)
                {
                    partnerattr.Value          = ADefaultPhoneMobile;
                    foundDefaultMobileLandLine = true;
                }
            }

            if (!foundDefaultEmailAddress)
            {
                PPartnerAttributeRow partnerattr = SaveDS.PPartnerAttribute.NewRowTyped();
                partnerattr.PartnerKey    = SaveDS.PPartner[0].PartnerKey;
                partnerattr.AttributeType = MPartnerConstants.ATTR_TYPE_EMAIL;
                partnerattr.Value         = ADefaultEmailAddress;
                partnerattr.Index         = 0;
                SaveDS.PPartnerAttribute.Rows.Add(partnerattr);
            }

            if (!foundDefaultPhoneLandLine)
            {
                PPartnerAttributeRow partnerattr = SaveDS.PPartnerAttribute.NewRowTyped();
                partnerattr.PartnerKey    = SaveDS.PPartner[0].PartnerKey;
                partnerattr.AttributeType = MPartnerConstants.ATTR_TYPE_PHONE;
                partnerattr.Value         = ADefaultPhoneLandline;
                partnerattr.Index         = 0;
                SaveDS.PPartnerAttribute.Rows.Add(partnerattr);
            }

            if (!foundDefaultMobileLandLine)
            {
                PPartnerAttributeRow partnerattr = SaveDS.PPartnerAttribute.NewRowTyped();
                partnerattr.PartnerKey    = SaveDS.PPartner[0].PartnerKey;
                partnerattr.AttributeType = MPartnerConstants.ATTR_TYPE_MOBILE_PHONE;
                partnerattr.Value         = ADefaultPhoneMobile;
                partnerattr.Index         = 0;
                SaveDS.PPartnerAttribute.Rows.Add(partnerattr);
            }

            // TODO: either reuse Partner Edit UIConnector
            // or check for changed partner key, or changed Partner Class, etc.

            // set Partner Short Name
            if (SaveDS.PPartner[0].PartnerClass == MPartnerConstants.PARTNERCLASS_PERSON)
            {
                SaveDS.PPartner[0].PartnerShortName =
                    Calculations.DeterminePartnerShortName(
                        SaveDS.PPerson[0].FamilyName,
                        SaveDS.PPerson[0].Title,
                        SaveDS.PPerson[0].FirstName,
                        SaveDS.PPerson[0].MiddleName1);
            }
            else if (SaveDS.PPartner[0].PartnerClass == MPartnerConstants.PARTNERCLASS_FAMILY)
            {
                // check if we have a valid family name
                if (SaveDS.PFamily[0].FamilyName.Trim().Length == 0)
                {
                    AVerificationResult.Add(new TVerificationResult("error", "Please specify the family name", "",
                                                                    "MaintainPartners.ErrMissingFamilyName", TResultSeverity.Resv_Critical));
                    return(false);
                }

                // check if we have a valid title
                if (SaveDS.PFamily[0].Title.Trim().Length == 0)
                {
                    AVerificationResult.Add(new TVerificationResult("error", "Please specify the title", "",
                                                                    "MaintainPartners.ErrMissingTitle", TResultSeverity.Resv_Critical));
                    return(false);
                }

                SaveDS.PPartner[0].PartnerShortName =
                    Calculations.DeterminePartnerShortName(
                        SaveDS.PFamily[0].FamilyName,
                        SaveDS.PFamily[0].Title,
                        SaveDS.PFamily[0].FirstName);
            }
            else if (SaveDS.PPartner[0].PartnerClass == MPartnerConstants.PARTNERCLASS_UNIT)
            {
                SaveDS.PPartner[0].PartnerShortName = SaveDS.PUnit[0].UnitName;
            }
            else if (SaveDS.PPartner[0].PartnerClass == MPartnerConstants.PARTNERCLASS_ORGANISATION)
            {
                // check if we have a valid organisation name
                if (SaveDS.POrganisation[0].OrganisationName.Trim().Length == 0)
                {
                    AVerificationResult.Add(new TVerificationResult("error", "Please specify the organisation name", "",
                                                                    "MaintainPartners.ErrMissingOrganisationName", TResultSeverity.Resv_Critical));
                    return(false);
                }

                SaveDS.PPartner[0].PartnerShortName = SaveDS.POrganisation[0].OrganisationName;
            }
            else if (SaveDS.PPartner[0].PartnerClass == MPartnerConstants.PARTNERCLASS_BANK)
            {
                SaveDS.PPartner[0].PartnerShortName = SaveDS.PBank[0].BranchName;
            }

            // change legacy addresses. create a new separate location for each partner
            if (SaveDS.PLocation[0].LocationKey == 0)
            {
                PLocationRow location = SaveDS.PLocation.NewRowTyped();
                DataUtilities.CopyAllColumnValues(SaveDS.PLocation[0], location);
                location.SiteKey     = DomainManager.GSiteKey;
                location.LocationKey = -1;
                SaveDS.PLocation.Rows.Clear();
                SaveDS.PLocation.Rows.Add(location);

                PPartnerLocationRow plocation = SaveDS.PPartnerLocation.NewRowTyped();
                DataUtilities.CopyAllColumnValues(SaveDS.PPartnerLocation[0], plocation);
                plocation.LocationKey = -1;
                plocation.SiteKey     = DomainManager.GSiteKey;
                SaveDS.PPartnerLocation[0].Delete();
                SaveDS.PPartnerLocation.Rows.Add(plocation);
            }

            // check if we have a valid country code
            if (SaveDS.PLocation[0].CountryCode.Trim().Length == 0)
            {
                AVerificationResult.Add(new TVerificationResult("error", "The country code is missing", TResultSeverity.Resv_Critical));
                return(false);
            }

            TDBTransaction Transaction      = new TDBTransaction();
            bool           WrongCountryCode = false;

            DBAccess.ReadTransaction(ref Transaction,
                                     delegate
            {
                WrongCountryCode = !PCountryAccess.Exists(SaveDS.PLocation[0].CountryCode, Transaction);
            });

            if (WrongCountryCode)
            {
                AVerificationResult.Add(new TVerificationResult("error", "The country code does not match a country", TResultSeverity.Resv_Critical));
                return(false);
            }

            DataSet ResponseDS = new PartnerEditTDS();
            TPartnerEditUIConnector uiconnector = new TPartnerEditUIConnector(SaveDS.PPartner[0].PartnerKey);

            try
            {
                TSubmitChangesResult result = uiconnector.SubmitChanges(
                    ref SaveDS,
                    ref ResponseDS,
                    out AVerificationResult);
                return(result == TSubmitChangesResult.scrOK);
            }
            catch (Exception e)
            {
                TLogging.Log(e.ToString());
                AVerificationResult.Add(new TVerificationResult("error", e.Message, TResultSeverity.Resv_Critical));
                return(false);
            }
        }
Esempio n. 12
0
        public static bool MaintainBankAccounts(
            string action,
            Int32 ABankingDetailsKey,
            Int64 APartnerKey,
            string AAccountName,
            string AIban,
            out TVerificationResultCollection AVerificationResult)
        {
            List <string>  Dummy1, Dummy2;
            string         Dummy3, Dummy4, Dummy5;
            PartnerEditTDS MainDS = GetPartnerDetails(APartnerKey, out Dummy1, out Dummy2, out Dummy3, out Dummy4, out Dummy5);

            AVerificationResult = new TVerificationResultCollection();

            AIban = AIban.Replace(" ", "");
            string BIC      = String.Empty;
            string BankName = String.Empty;

            if ((action == "create" || action == "edit"))
            {
                // Validate IBAN, and calculate the BIC
                if (!ValidateIBAN(AIban, out BIC, out BankName, out AVerificationResult))
                {
                    return(false);
                }
            }

            if (action == "create")
            {
                PartnerEditTDSPBankingDetailsRow row = MainDS.PBankingDetails.NewRowTyped();
                row.BankingDetailsKey = -1;
                row.BankingType       = 0; // BANK ACCOUNT
                row.AccountName       = AAccountName;
                row.Iban        = AIban;
                row.BankKey     = FindOrCreateBank(BIC, BankName);
                row.MainAccount = MainDS.PBankingDetails.Count == 0;
                MainDS.PBankingDetails.Rows.Add(row);

                PPartnerBankingDetailsRow pdrow = MainDS.PPartnerBankingDetails.NewRowTyped();
                pdrow.PartnerKey        = APartnerKey;
                pdrow.BankingDetailsKey = -1;
                MainDS.PPartnerBankingDetails.Rows.Add(pdrow);

                DataSet ResponseDS = new PartnerEditTDS();
                TPartnerEditUIConnector uiconnector = new TPartnerEditUIConnector(APartnerKey);

                try
                {
                    TSubmitChangesResult result = uiconnector.SubmitChanges(
                        ref MainDS,
                        ref ResponseDS,
                        out AVerificationResult);

                    return(result == TSubmitChangesResult.scrOK);
                }
                catch (Exception e)
                {
                    TLogging.Log(e.ToString());
                    AVerificationResult.Add(new TVerificationResult("error", e.Message, TResultSeverity.Resv_Critical));
                    return(false);
                }
            }
            else if (action == "edit")
            {
                foreach (PartnerEditTDSPBankingDetailsRow row in MainDS.PBankingDetails.Rows)
                {
                    if (row.BankingDetailsKey == ABankingDetailsKey)
                    {
                        row.AccountName = AAccountName;
                        row.Iban        = AIban;
                        row.BankKey     = FindOrCreateBank(BIC, BankName);
                    }
                }

                DataSet ResponseDS = new PartnerEditTDS();
                TPartnerEditUIConnector uiconnector = new TPartnerEditUIConnector(APartnerKey);

                try
                {
                    TSubmitChangesResult result = uiconnector.SubmitChanges(
                        ref MainDS,
                        ref ResponseDS,
                        out AVerificationResult);

                    return(result == TSubmitChangesResult.scrOK);
                }
                catch (Exception e)
                {
                    TLogging.Log(e.ToString());
                    AVerificationResult.Add(new TVerificationResult("error", e.Message, TResultSeverity.Resv_Critical));
                    return(false);
                }
            }
            else if (action == "delete")
            {
                foreach (PPartnerBankingDetailsRow row in MainDS.PPartnerBankingDetails.Rows)
                {
                    if (row.BankingDetailsKey == ABankingDetailsKey)
                    {
                        row.Delete();
                    }
                }

                bool wasMainAccount = false;
                PartnerEditTDSPBankingDetailsRow otherAccount = null;
                foreach (PartnerEditTDSPBankingDetailsRow row in MainDS.PBankingDetails.Rows)
                {
                    if (row.BankingDetailsKey == ABankingDetailsKey)
                    {
                        if (!row.IsMainAccountNull())
                        {
                            wasMainAccount = row.MainAccount;
                        }
                        row.Delete();
                    }
                    else if (otherAccount == null)
                    {
                        otherAccount = row;
                    }
                }

                // make another bank account the main account
                if (wasMainAccount && (otherAccount != null))
                {
                    otherAccount.MainAccount = true;
                }

                DataSet ResponseDS = new PartnerEditTDS();
                TPartnerEditUIConnector uiconnector = new TPartnerEditUIConnector(APartnerKey);

                try
                {
                    TSubmitChangesResult result = uiconnector.SubmitChanges(
                        ref MainDS,
                        ref ResponseDS,
                        out AVerificationResult);

                    return(result == TSubmitChangesResult.scrOK);
                }
                catch (Exception e)
                {
                    TLogging.Log(e.ToString());
                    AVerificationResult.Add(new TVerificationResult("error", e.Message, TResultSeverity.Resv_Critical));
                    return(false);
                }
            }

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

            return(false);
        }
Esempio n. 13
0
        /// Upgrade to version 2015-01
        public static bool UpgradeDatabase201412_201501()
        {
            // There are no new tables and fields

            TDBTransaction       SubmitChangesTransaction = null;
            TSubmitChangesResult SubmissionResult         = TSubmitChangesResult.scrError;

            DBAccess.GDBAccessObj.BeginAutoTransaction(IsolationLevel.Serializable, ref SubmitChangesTransaction,
                                                       ref SubmissionResult,
                                                       delegate
            {
                PPartnerAttributeTable partnerattributes = new PPartnerAttributeTable();
                PPartnerLocationTable partnerlocations   = PPartnerLocationAccess.LoadAll(SubmitChangesTransaction);

                // this update only works for very simple databases, only one partner location record per partner...
                if (partnerlocations.Count > 1000)
                {
                    throw new Exception("the upgrade has not been optimized for huge databases");
                }

                List <Int64> PartnerKeys = new List <Int64>();

                foreach (PPartnerLocationRow partnerlocation in partnerlocations.Rows)
                {
                    if (!PartnerKeys.Contains(partnerlocation.PartnerKey))
                    {
                        PartnerKeys.Add(partnerlocation.PartnerKey);
                    }
                    else
                    {
                        TLogging.Log("several locations for partner " + partnerlocation.PartnerKey.ToString());
                    }
                }

                // Number for the p_sequence_i Column. Gets increased with every p_partner_attribute record that gets produced!
                int SequenceNumber = 0;

                foreach (Int64 partnerkey in PartnerKeys)
                {
                    // Get that Partner's p_partner_location records from PPartnerLocationRecords
                    DataRow[] CurrentRows = partnerlocations.Select(PPartnerLocationTable.GetPartnerKeyDBName() + " = " + partnerkey.ToString());

                    if (CurrentRows.Length == 0)
                    {
                        continue;
                    }

                    DataTable PPartnersLocationsDT = GetNewPPartnerLocationTableInstance();

                    foreach (DataRow r in CurrentRows)
                    {
                        PPartnersLocationsDT.Rows.Add(r.ItemArray);
                    }

                    TLocationPK bestAddress = Calculations.DetermineBestAddress(PPartnersLocationsDT);

                    int IndexPhone  = 0;
                    int IndexEmail  = 0;
                    int IndexFax    = 0;
                    int IndexUrl    = 0;
                    int IndexMobile = 0;

                    List <string> AvoidDuplicates = new List <string>();
                    string AttributeConcatenated;

                    foreach (PPartnerLocationRow partnerlocation in PPartnersLocationsDT.Rows)
                    {
                        bool primaryAddress =
                            (bestAddress.LocationKey == partnerlocation.LocationKey && bestAddress.SiteKey == partnerlocation.SiteKey);
                        bool currentAddress  = (((int)partnerlocation[PARTNERLOCATION_ICON_COLUMN]) == 1);
                        bool businessAddress = (partnerlocation.LocationType == "BUSINESS" || partnerlocation.LocationType == "FIELD");
                        // TODO: avoid duplicate entries with the same type

                        if (!partnerlocation.IsEmailAddressNull())
                        {
                            PPartnerAttributeRow partnerattribute = partnerattributes.NewRowTyped();
                            partnerattribute.Sequence             = SequenceNumber++;
                            partnerattribute.PartnerKey           = partnerlocation.PartnerKey;
                            partnerattribute.Value               = partnerlocation.EmailAddress;
                            partnerattribute.AttributeType       = MPartnerConstants.ATTR_TYPE_EMAIL;
                            partnerattribute.Current             = currentAddress;
                            partnerattribute.Primary             = primaryAddress;
                            partnerattribute.Index               = IndexEmail++;
                            partnerattribute.Specialised         = businessAddress;
                            partnerattribute.NoLongerCurrentFrom = partnerlocation.DateGoodUntil;

                            AttributeConcatenated = ConcatPartnerAttributes(partnerattribute);

                            if (!AvoidDuplicates.Contains(AttributeConcatenated))
                            {
                                partnerattributes.Rows.Add(partnerattribute);
                                AvoidDuplicates.Add(AttributeConcatenated);
                            }
                            else
                            {
                                TLogging.Log("dropping duplicate " + AttributeConcatenated);
                            }

                            partnerlocation.SetEmailAddressNull();
                        }

                        if (!partnerlocation.IsTelephoneNumberNull())
                        {
                            if (!partnerlocation.IsExtensionNull())
                            {
                                partnerlocation.TelephoneNumber += "-" + partnerlocation.Extension;
                            }

                            PPartnerAttributeRow partnerattribute = partnerattributes.NewRowTyped();
                            partnerattribute.Sequence             = SequenceNumber++;
                            partnerattribute.PartnerKey           = partnerlocation.PartnerKey;
                            partnerattribute.Value               = partnerlocation.TelephoneNumber;
                            partnerattribute.AttributeType       = MPartnerConstants.ATTR_TYPE_PHONE;
                            partnerattribute.Current             = currentAddress;
                            partnerattribute.Primary             = primaryAddress;
                            partnerattribute.Index               = IndexPhone++;
                            partnerattribute.Specialised         = businessAddress;
                            partnerattribute.NoLongerCurrentFrom = partnerlocation.DateGoodUntil;

                            AttributeConcatenated = ConcatPartnerAttributes(partnerattribute);

                            if (!AvoidDuplicates.Contains(AttributeConcatenated))
                            {
                                partnerattributes.Rows.Add(partnerattribute);
                                AvoidDuplicates.Add(AttributeConcatenated);
                            }
                            else
                            {
                                TLogging.Log("dropping duplicate " + AttributeConcatenated);
                            }

                            partnerlocation.SetTelephoneNumberNull();
                        }

                        if (!partnerlocation.IsFaxNumberNull())
                        {
                            if (!partnerlocation.IsFaxExtensionNull())
                            {
                                partnerlocation.FaxNumber += "-" + partnerlocation.FaxExtension;
                            }

                            PPartnerAttributeRow partnerattribute = partnerattributes.NewRowTyped();
                            partnerattribute.Sequence             = SequenceNumber++;
                            partnerattribute.PartnerKey           = partnerlocation.PartnerKey;
                            partnerattribute.Value               = partnerlocation.FaxNumber;
                            partnerattribute.AttributeType       = MPartnerConstants.ATTR_TYPE_FAX;
                            partnerattribute.Current             = currentAddress;
                            partnerattribute.Primary             = primaryAddress;
                            partnerattribute.Index               = IndexFax++;
                            partnerattribute.Specialised         = businessAddress;
                            partnerattribute.NoLongerCurrentFrom = partnerlocation.DateGoodUntil;

                            AttributeConcatenated = ConcatPartnerAttributes(partnerattribute);

                            if (!AvoidDuplicates.Contains(AttributeConcatenated))
                            {
                                partnerattributes.Rows.Add(partnerattribute);
                                AvoidDuplicates.Add(AttributeConcatenated);
                            }
                            else
                            {
                                TLogging.Log("dropping duplicate " + AttributeConcatenated);
                            }

                            partnerlocation.SetFaxNumberNull();
                        }

                        if (!partnerlocation.IsAlternateTelephoneNull())
                        {
                            PPartnerAttributeRow partnerattribute = partnerattributes.NewRowTyped();
                            partnerattribute.Sequence             = SequenceNumber++;
                            partnerattribute.PartnerKey           = partnerlocation.PartnerKey;
                            partnerattribute.Value               = partnerlocation.AlternateTelephone;
                            partnerattribute.AttributeType       = MPartnerConstants.ATTR_TYPE_PHONE;
                            partnerattribute.Current             = currentAddress;
                            partnerattribute.Primary             = primaryAddress;
                            partnerattribute.Index               = IndexPhone++;
                            partnerattribute.Specialised         = businessAddress;
                            partnerattribute.NoLongerCurrentFrom = partnerlocation.DateGoodUntil;

                            AttributeConcatenated = ConcatPartnerAttributes(partnerattribute);

                            if (!AvoidDuplicates.Contains(AttributeConcatenated))
                            {
                                partnerattributes.Rows.Add(partnerattribute);
                                AvoidDuplicates.Add(AttributeConcatenated);
                            }
                            else
                            {
                                TLogging.Log("dropping duplicate " + AttributeConcatenated);
                            }

                            partnerlocation.SetAlternateTelephoneNull();
                        }

                        if (!partnerlocation.IsMobileNumberNull())
                        {
                            PPartnerAttributeRow partnerattribute = partnerattributes.NewRowTyped();
                            partnerattribute.Sequence             = SequenceNumber++;
                            partnerattribute.PartnerKey           = partnerlocation.PartnerKey;
                            partnerattribute.Value               = partnerlocation.MobileNumber;
                            partnerattribute.AttributeType       = MPartnerConstants.ATTR_TYPE_MOBILE_PHONE;
                            partnerattribute.Current             = currentAddress;
                            partnerattribute.Primary             = primaryAddress;
                            partnerattribute.Index               = IndexMobile++;
                            partnerattribute.Specialised         = businessAddress;
                            partnerattribute.NoLongerCurrentFrom = partnerlocation.DateGoodUntil;

                            AttributeConcatenated = ConcatPartnerAttributes(partnerattribute);

                            if (!AvoidDuplicates.Contains(AttributeConcatenated))
                            {
                                partnerattributes.Rows.Add(partnerattribute);
                                AvoidDuplicates.Add(AttributeConcatenated);
                            }
                            else
                            {
                                TLogging.Log("dropping duplicate " + AttributeConcatenated);
                            }

                            partnerlocation.SetMobileNumberNull();
                        }

                        if (!partnerlocation.IsUrlNull())
                        {
                            PPartnerAttributeRow partnerattribute = partnerattributes.NewRowTyped();
                            partnerattribute.Sequence             = SequenceNumber++;
                            partnerattribute.PartnerKey           = partnerlocation.PartnerKey;
                            partnerattribute.Value               = partnerlocation.Url;
                            partnerattribute.AttributeType       = MPartnerConstants.ATTR_TYPE_WEBSITE;
                            partnerattribute.Current             = currentAddress;
                            partnerattribute.Primary             = primaryAddress;
                            partnerattribute.Index               = IndexUrl++;
                            partnerattribute.Specialised         = businessAddress;
                            partnerattribute.NoLongerCurrentFrom = partnerlocation.DateGoodUntil;

                            AttributeConcatenated = ConcatPartnerAttributes(partnerattribute);

                            if (!AvoidDuplicates.Contains(AttributeConcatenated))
                            {
                                partnerattributes.Rows.Add(partnerattribute);
                                AvoidDuplicates.Add(AttributeConcatenated);
                            }
                            else
                            {
                                TLogging.Log("dropping duplicate " + AttributeConcatenated);
                            }

                            partnerlocation.SetUrlNull();
                        }
                    }
                }

                PPartnerLocationAccess.SubmitChanges(partnerlocations, SubmitChangesTransaction);
                PPartnerAttributeAccess.SubmitChanges(partnerattributes, SubmitChangesTransaction);
                SubmissionResult = TSubmitChangesResult.scrOK;
            });
            return(true);
        }
        /// <summary>
        /// First loads the extractTable needed. Goes throught all the Partners in the extract,  If the partner already has the subscription, returns all those partners back to client.  If the partner doesn't have the subscription, saves this
        /// subscription to those partners.
        /// </summary>
        /// <returns>void</returns>
        private void SubmitChangesInternal()
        {
            TDBTransaction SubmitChangesTransaction;
            TSubmitChangesResult SubmissionResult = TSubmitChangesResult.scrOK;
            MExtractTable ExtractDT;
            PSubscriptionTable SubscriptionTable;

            PPartnerTable PartnerTable;
            Int32 RowCounter;
            Int32 PartnersInExtract;
            StringCollection RequiredColumns;
            StringCollection RequiredColumns2;

            if (FInspectDT != null)
            {
                // Initialisations
                FVerificationResult = new TVerificationResultCollection();
                ExtractDT = new MExtractTable();
                SubscriptionTable = new PSubscriptionTable();
                FSubmissionDT = SubscriptionTable.Clone();
                ((TTypedDataTable)FSubmissionDT).InitVars();
                PartnerTable = new PPartnerTable();
                RequiredColumns = new StringCollection();
                RequiredColumns.Add(MExtractTable.GetPartnerKeyDBName());
                RequiredColumns2 = new StringCollection();
                RequiredColumns2.Add(PPartnerTable.GetPartnerKeyDBName());
                RequiredColumns2.Add(PPartnerTable.GetPartnerShortNameDBName());
                RowCounter = 0;

                // Set up asynchronous execution
                FAsyncExecProgress.ProgressState = TAsyncExecProgressState.Aeps_Executing;
                FAsyncExecProgress.ProgressInformation = "Checking Partners' Subscriptions...";
                try
                {
                    SubmitChangesTransaction = DBAccess.GDBAccessObj.BeginTransaction(IsolationLevel.Serializable);
//                  TLogging.LogAtLevel(7, "TExtractsAddSubscriptionsUIConnector.SubmitChangesInternal: loading Subscriptions for ExtractID " + FExtractID.ToString() + "...");
                    ExtractDT = MExtractAccess.LoadViaMExtractMaster(FExtractID, RequiredColumns, SubmitChangesTransaction);
                    PartnersInExtract = ExtractDT.Rows.Count;
//                  TLogging.LogAtLevel(7, "TExtractsAddSubscriptionsUIConnector.SubmitChangesInternal: ExtractID has " + PartnersInExtract.ToString() + " Partners.");

                    // Go throught all the Partners in the extract
                    foreach (MExtractRow ExtractRow in ExtractDT.Rows)
                    {
                        RowCounter = RowCounter + 1;

                        // Calculate how much Partners we have checked. Let all Partners be a maximum of 70%.
                        FAsyncExecProgress.ProgressPercentage =
                            Convert.ToInt16((((double)RowCounter / (double)PartnersInExtract) * 100) * (MAX_PERCENTAGE_CHECKS / 100.0));
                        TLogging.LogAtLevel(7, "TExtractsAddSubscriptionsUIConnector.SubmitChangesInternal: loadbyPrimaryKey");

                        SubscriptionTable = PSubscriptionAccess.LoadByPrimaryKey(
                            FInspectDT[0].PublicationCode,
                            ExtractRow.PartnerKey,
                            SubmitChangesTransaction);

                        // if the Partner does not yet have the subscription, add the subscription to this partner.
                        if (SubscriptionTable.Rows.Count == 0)
                        {
                            TLogging.LogAtLevel(
                                7,
                                "TExtractsAddSubscriptionsUIConnector.SubmitChangesInternal: will add Subscription to Partner with PartnerKey " +
                                ExtractRow.PartnerKey.ToString());
                            FInspectDT[0].PartnerKey = ExtractRow.PartnerKey;
                            TLogging.LogAtLevel(7, "TExtractsAddSubscriptionsUIConnector.SubmitChangesInternal: importing Row into FSubmissionDT...");
                            FSubmissionDT.ImportRow(FInspectDT[0]);
                        }
                        else
                        {
                            // The partner already has this Subscription: add the partner to the ResponseTable
//                          TLogging.LogAtLevel(7, "TExtractsAddSubscriptionsUIConnector.SubmitChangesInternal: won't add Subscription to Partner with PartnerKey " + ExtractRow.PartnerKey.ToString());
                            PartnerTable = PPartnerAccess.LoadByPrimaryKey(ExtractRow.PartnerKey, RequiredColumns2, SubmitChangesTransaction);

                            if (FResponseDT == null)
                            {
                                FResponseDT = PartnerTable.Clone();
                            }

                            FResponseDT.ImportRow(PartnerTable[0]);
                        }
                    }

                    TLogging.LogAtLevel(7, "TExtractsAddSubscriptionsUIConnector.SubmitChangesInternal: Finished checking Partner's Subscriptions.");

                    if (FSubmissionDT.Rows.Count > 0)
                    {
                        // Submit the Partners with new Subscriptions to the PSubscription Table.
                        FAsyncExecProgress.ProgressInformation = "Adding Subscriptions to " + FSubmissionDT.Rows.Count.ToString() + " Partners...";
                        FAsyncExecProgress.ProgressPercentage = MAX_PERCENTAGE_CHECKS;
//                      TLogging.LogAtLevel(7, "TExtractsAddSubscriptionsUIConnector.SubmitChangesInternal: " + FAsyncExecProgress.ProgressInformation);

                        PSubscriptionAccess.SubmitChanges((PSubscriptionTable)FSubmissionDT, SubmitChangesTransaction);
                    }
                    else
                    {
                        TLogging.LogAtLevel(
                            7,
                            "TExtractsAddSubscriptionsUIConnector.SubmitChangesInternal: no Subscriptions were added to Partners because all the Partners in the Extract already had this Subscription.");
                    }

                    DBAccess.GDBAccessObj.CommitTransaction();
                }
                catch (Exception Exp)
                {
                    DBAccess.GDBAccessObj.RollbackTransaction();

                    TLogging.LogAtLevel(7,
                        "TExtractsAddSubscriptionsUIConnector.SubmitChangesInternal: Exception occured, Transaction ROLLED BACK. Exception: " +
                        Exp.ToString());

                    FSubmitResult = TSubmitChangesResult.scrError;
                    FSubmitException = Exp;
                    FAsyncExecProgress.ProgressState = TAsyncExecProgressState.Aeps_Stopped;

                    return;
                }
            }
            else
            {
                SubmissionResult = TSubmitChangesResult.scrNothingToBeSaved;
            }

            // if no values at response table, it needs to be created. If not creates, will raise exeption at client side.
            if (FResponseDT == null)
            {
                FResponseDT = new DataTable();
            }

            FAsyncExecProgress.ProgressPercentage = 100;
            FAsyncExecProgress.ProgressState = TAsyncExecProgressState.Aeps_Finished;
            FSubmitResult = SubmissionResult;
        }
 /// <summary>
 /// todoComment
 /// </summary>
 /// <param name="AResponseDT"></param>
 /// <param name="AVerificationResult"></param>
 /// <param name="ASubmitChangesResult"></param>
 public void SubmitChangesAsyncResult(out DataTable AResponseDT,
     out TVerificationResultCollection AVerificationResult,
     out TSubmitChangesResult ASubmitChangesResult)
 {
     if (FSubmitException == null)
     {
         AResponseDT = FResponseDT;
         AVerificationResult = FVerificationResult;
         ASubmitChangesResult = FSubmitResult;
     }
     else
     {
         throw FSubmitException;
     }
 }
        /// <summary>
        /// First loads the extractTable needed. Goes throught all the Partners in the extract,  If the partner already has the subscription, returns all those partners back to client.  If the partner doesn't have the subscription, saves this
        /// subscription to those partners.
        /// </summary>
        /// <returns>void</returns>
        private void SubmitChangesInternal()
        {
            TDBTransaction       SubmitChangesTransaction = null;
            TSubmitChangesResult SubmissionResult         = TSubmitChangesResult.scrNothingToBeSaved;
            MExtractTable        ExtractDT;
            PSubscriptionTable   SubscriptionTable;

            PPartnerTable    PartnerTable;
            Int32            RowCounter;
            Int32            PartnersInExtract;
            StringCollection RequiredColumns;
            StringCollection RequiredColumns2;

            if (FInspectDT != null)
            {
                // Initialisations
                FVerificationResult = new TVerificationResultCollection();
                ExtractDT           = new MExtractTable();
                SubscriptionTable   = new PSubscriptionTable();
                FSubmissionDT       = SubscriptionTable.Clone();
                ((TTypedDataTable)FSubmissionDT).InitVars();
                PartnerTable    = new PPartnerTable();
                RequiredColumns = new StringCollection();
                RequiredColumns.Add(MExtractTable.GetPartnerKeyDBName());
                RequiredColumns2 = new StringCollection();
                RequiredColumns2.Add(PPartnerTable.GetPartnerKeyDBName());
                RequiredColumns2.Add(PPartnerTable.GetPartnerShortNameDBName());
                RowCounter = 0;

                // Set up asynchronous execution
                TProgressTracker.SetCurrentState(FProgressID, "Checking Partners' Subscriptions...", 0.0m);


                DBAccess.GDBAccessObj.BeginAutoTransaction(IsolationLevel.Serializable, ref SubmitChangesTransaction,
                                                           ref SubmissionResult,
                                                           delegate
                {
                    try
                    {
                        //                  TLogging.LogAtLevel(7, "TExtractsAddSubscriptionsUIConnector.SubmitChangesInternal: loading Subscriptions for ExtractID " + FExtractID.ToString() + "...");
                        ExtractDT         = MExtractAccess.LoadViaMExtractMaster(FExtractID, RequiredColumns, SubmitChangesTransaction);
                        PartnersInExtract = ExtractDT.Rows.Count;
                        //                  TLogging.LogAtLevel(7, "TExtractsAddSubscriptionsUIConnector.SubmitChangesInternal: ExtractID has " + PartnersInExtract.ToString() + " Partners.");

                        // Go throught all the Partners in the extract
                        foreach (MExtractRow ExtractRow in ExtractDT.Rows)
                        {
                            RowCounter = RowCounter + 1;

                            // Calculate how much Partners we have checked. Let all Partners be a maximum of 70%.
                            TProgressTracker.SetCurrentState(
                                FProgressID,
                                string.Empty,
                                Convert.ToInt16((((double)RowCounter / (double)PartnersInExtract) * 100) * (MAX_PERCENTAGE_CHECKS / 100.0)));
                            TLogging.LogAtLevel(7, "TExtractsAddSubscriptionsUIConnector.SubmitChangesInternal: loadbyPrimaryKey");

                            SubscriptionTable = PSubscriptionAccess.LoadByPrimaryKey(
                                FInspectDT[0].PublicationCode,
                                ExtractRow.PartnerKey,
                                SubmitChangesTransaction);

                            // if the Partner does not yet have the subscription, add the subscription to this partner.
                            if (SubscriptionTable.Rows.Count == 0)
                            {
                                TLogging.LogAtLevel(
                                    7,
                                    "TExtractsAddSubscriptionsUIConnector.SubmitChangesInternal: will add Subscription to Partner with PartnerKey "
                                    +
                                    ExtractRow.PartnerKey.ToString());
                                FInspectDT[0].PartnerKey = ExtractRow.PartnerKey;
                                TLogging.LogAtLevel(7,
                                                    "TExtractsAddSubscriptionsUIConnector.SubmitChangesInternal: importing Row into FSubmissionDT...");
                                FSubmissionDT.ImportRow(FInspectDT[0]);
                            }
                            else
                            {
                                // The partner already has this Subscription: add the partner to the ResponseTable
                                //                          TLogging.LogAtLevel(7, "TExtractsAddSubscriptionsUIConnector.SubmitChangesInternal: won't add Subscription to Partner with PartnerKey " + ExtractRow.PartnerKey.ToString());
                                PartnerTable = PPartnerAccess.LoadByPrimaryKey(ExtractRow.PartnerKey, RequiredColumns2, SubmitChangesTransaction);

                                if (FResponseDT == null)
                                {
                                    FResponseDT = PartnerTable.Clone();
                                }

                                FResponseDT.ImportRow(PartnerTable[0]);
                            }
                        }

                        TLogging.LogAtLevel(7,
                                            "TExtractsAddSubscriptionsUIConnector.SubmitChangesInternal: Finished checking Partner's Subscriptions.");

                        if (FSubmissionDT.Rows.Count > 0)
                        {
                            // Submit the Partners with new Subscriptions to the PSubscription Table.
                            TProgressTracker.SetCurrentState(
                                FProgressID,
                                "Adding Subscriptions to " + FSubmissionDT.Rows.Count.ToString() + " Partners...",
                                MAX_PERCENTAGE_CHECKS);
                            //                      TLogging.LogAtLevel(7, "TExtractsAddSubscriptionsUIConnector.SubmitChangesInternal: " + FAsyncExecProgress.ProgressInformation);

                            PSubscriptionAccess.SubmitChanges((PSubscriptionTable)FSubmissionDT, SubmitChangesTransaction);
                        }
                        else
                        {
                            TLogging.LogAtLevel(
                                7,
                                "TExtractsAddSubscriptionsUIConnector.SubmitChangesInternal: no Subscriptions were added to Partners because all the Partners in the Extract already had this Subscription.");
                        }

                        SubmissionResult = TSubmitChangesResult.scrOK;
                    }
                    catch (Exception Exp)
                    {
                        TLogging.LogAtLevel(7,
                                            "TExtractsAddSubscriptionsUIConnector.SubmitChangesInternal: Exception occured, Transaction will get ROLLED BACK. Exception: "
                                            +
                                            Exp.ToString());

                        SubmissionResult = TSubmitChangesResult.scrError;
                        FSubmitResult    = SubmissionResult;
                        FSubmitException = Exp;
                        TProgressTracker.CancelJob(FProgressID);

                        return;
                    }
                });
            }

            // if no values at response table, it needs to be created. If not creates, will raise exeption at client side.
            if (FResponseDT == null)
            {
                FResponseDT = new DataTable();
            }

            TProgressTracker.FinishJob(FProgressID);
            FSubmitResult = SubmissionResult;
        }