public static bool GetBestAddress(Int64 APartnerKey,
            out PLocationTable AAddress,
            out string ACountryNameLocal)
        {
            bool NewTransaction;
            TDBTransaction Transaction = DBAccess.GDBAccessObj.GetNewOrExistingTransaction(IsolationLevel.ReadCommitted,
                TEnforceIsolationLevel.eilMinimum, out NewTransaction);

            bool ResultValue = false;

            try
            {
                ResultValue = TAddressTools.GetBestAddress(APartnerKey,
                    out AAddress,
                    out ACountryNameLocal,
                    Transaction);
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (NewTransaction)
                {
                    DBAccess.GDBAccessObj.RollbackTransaction();
                }
            }
            return ResultValue;
        }
        private void SetupGrid()
        {
            // create a new table
            FCriteriaData.Columns.Add(PBankTable.GetPartnerKeyDBName(), Type.GetType("System.Int64"));
            FCriteriaData.Columns.Add(BankTDSPBankTable.GetSiteKeyDBName(), Type.GetType("System.Int64"));
            FCriteriaData.Columns.Add(BankTDSPBankTable.GetLocationKeyDBName(), Type.GetType("System.Int32"));
            FCriteriaData.Columns.Add(PBankTable.GetBranchNameDBName(), Type.GetType("System.String"));
            FCriteriaData.Columns.Add(PBankTable.GetBranchCodeDBName(), Type.GetType("System.String"));
            FCriteriaData.Columns.Add(PBankTable.GetBicDBName(), Type.GetType("System.String"));
            FCriteriaData.Columns.Add(BankTDSPBankTable.GetCityDBName(), Type.GetType("System.String"));
            FCriteriaData.Columns.Add(BankTDSPBankTable.GetCountryCodeDBName(), Type.GetType("System.String"));
            FCriteriaData.Columns.Add(BankTDSPBankTable.GetStatusCodeDBName(), Type.GetType("System.String"));

            FCriteriaData.PrimaryKey = new DataColumn[] {
                FCriteriaData.Columns[PBankTable.GetPartnerKeyDBName()],
                FCriteriaData.Columns[BankTDSPBankTable.GetSiteKeyDBName()], FCriteriaData.Columns[BankTDSPBankTable.GetLocationKeyDBName()]
            };
            FCriteriaData.DefaultView.AllowNew = false;

            // add columns to the grid
            grdDetails.Columns.Clear();
            grdDetails.AddTextColumn("Partner Key", FCriteriaData.Columns[PBankTable.GetPartnerKeyDBName()], 80);
            grdDetails.AddTextColumn("Bank Name", FCriteriaData.Columns[PBankTable.GetBranchNameDBName()]);
            grdDetails.AddTextColumn("Bank/Branch Code", FCriteriaData.Columns[PBankTable.GetBranchCodeDBName()], 120);
            grdDetails.AddTextColumn("BIC/SWIFT Code", FCriteriaData.Columns[PBankTable.GetBicDBName()], 110);
            grdDetails.AddTextColumn("Status", FCriteriaData.Columns[BankTDSPBankTable.GetStatusCodeDBName()], 70);
            grdDetails.AddTextColumn("City", FCriteriaData.Columns[PLocationTable.GetCityDBName()], 80);
            grdDetails.AddTextColumn("Country", FCriteriaData.Columns[PLocationTable.GetCountryCodeDBName()], 60);

            grdDetails.DoubleClickCell           += new TDoubleClickCellEventHandler(grdDetails_DoubleClickCell);
            grdDetails.EnterKeyPressed           += new TKeyPressedEventHandler(grdDetails_EnterKey);
            grdDetails.Selection.FocusRowEntered += new SourceGrid.RowEventHandler(this.FocusedRowChanged);
        }
Exemple #3
0
        public static bool GetBestAddress(Int64 APartnerKey,
                                          out PLocationTable AAddress,
                                          out string ACountryNameLocal)
        {
            bool           NewTransaction;
            TDataBase      db          = DBAccess.Connect("GetBestAddress");
            TDBTransaction Transaction = db.GetNewOrExistingTransaction(IsolationLevel.ReadCommitted,
                                                                        out NewTransaction);

            bool ResultValue = false;

            try
            {
                ResultValue = TAddressTools.GetBestAddress(APartnerKey,
                                                           out AAddress,
                                                           out ACountryNameLocal,
                                                           Transaction);
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (NewTransaction)
                {
                    Transaction.Rollback();
                }
            }
            return(ResultValue);
        }
Exemple #4
0
        public static bool GetBestAddress(Int64 APartnerKey,
                                          out PLocationTable AAddress,
                                          out PPartnerLocationTable APartnerLocation,
                                          out string ACountryNameLocal,
                                          out string AEmailAddress)
        {
            bool           NewTransaction;
            TDBTransaction Transaction = DBAccess.GDBAccessObj.GetNewOrExistingTransaction(IsolationLevel.ReadCommitted,
                                                                                           TEnforceIsolationLevel.eilMinimum, out NewTransaction);

            bool ResultValue = false;

            try
            {
                ResultValue = TAddressTools.GetBestAddress(APartnerKey,
                                                           out AAddress,
                                                           out APartnerLocation,
                                                           out ACountryNameLocal,
                                                           out AEmailAddress,
                                                           Transaction);
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (NewTransaction)
                {
                    DBAccess.GDBAccessObj.RollbackTransaction();
                }
            }
            return(ResultValue);
        }
 private DataTable GetCountyListTable(TDBTransaction AReadTransaction, string ATableName)
 {
     return(DBAccess.GetDBAccessObj(AReadTransaction).SelectDT("SELECT DISTINCT " +
                                                               PLocationTable.GetCountryCodeDBName() + ", " +
                                                               PLocationTable.GetCountyDBName() + " FROM PUB." +
                                                               PLocationTable.GetTableDBName(), ATableName, AReadTransaction));
 }
        /// <summary>
        /// Called when data got saved in the screen. This Method takes over changed data
        /// into FMainDS, which is different than the Partner Edit screen's FMainDS, in
        /// order to have current data on which decisions on whether to refresh certain
        /// parts of the 'Overview' need to be updated.
        /// </summary>
        /// <param name="APartnerAttributesOrRelationsChanged">NOT USED IN THIS CONTEXT!  (Set to true by the SaveChanges Method
        /// of the Partner Edit screen if PartnerAttributes or Relationships have changed.)</param>
        public void RefreshPersonnelDataAfterMerge(bool APartnerAttributesOrRelationsChanged)
        {
            //
            // Need to merge Tables from PartnerEditTDS into IndividualDataTDS so the updated s_modification_id_t of modififed Rows is held correctly in IndividualDataTDS, too!
            //

            // ...but first empty relevant DataTables to ensure that DataRows that got deleted in FPartnerEditTDS are reflected in FMainDS (just performing a Merge wouldn't remove them!)
            if (FMainDS.Tables.Contains(PPartnerLocationTable.GetTableName()))
            {
                FMainDS.Tables[PPartnerLocationTable.GetTableName()].Rows.Clear();
            }

            if (FMainDS.Tables.Contains(PLocationTable.GetTableName()))
            {
                FMainDS.Tables[PLocationTable.GetTableName()].Rows.Clear();
            }

            if (FMainDS.Tables.Contains(PPartnerRelationshipTable.GetTableName()))
            {
                FMainDS.Tables[PPartnerRelationshipTable.GetTableName()].Rows.Clear();
            }

            // Now perform the Merge operation
            FMainDS.Merge(FPartnerEditTDS);

            // Call AcceptChanges on IndividualDataTDS so that we don't have any changed data anymore (this is done to PartnerEditTDS, too, after this Method returns)!
            FMainDS.AcceptChanges();
        }
Exemple #7
0
        /// find the current best address for the partner
        public static bool GetBestAddress(Int64 APartnerKey,
                                          out PLocationTable AAddress,
                                          out string ACountryNameLocal,
                                          TDBTransaction ATransaction,
                                          bool AOnlySendMail = false)
        {
            AAddress          = null;
            ACountryNameLocal = "";

            DataSet PartnerLocationsDS = new DataSet();

            PartnerLocationsDS.Tables.Add(new PPartnerLocationTable());
            PartnerLocationsDS.Tables.Add(new PCountryTable());
            DataTable     PartnerLocationTable = PartnerLocationsDS.Tables[PPartnerLocationTable.GetTableName()];
            PCountryTable CountryTable         = (PCountryTable)PartnerLocationsDS.Tables[PCountryTable.GetTableName()];

            CountryTable.DefaultView.Sort = PCountryTable.GetCountryCodeDBName();

            // add special column BestAddress and Icon
            PartnerLocationTable.Columns.Add(new System.Data.DataColumn("BestAddress", typeof(Boolean)));
            PartnerLocationTable.Columns.Add(new System.Data.DataColumn("Icon", typeof(Int32)));

            // find all locations of the partner, put it into a dataset
            PPartnerLocationAccess.LoadViaPPartner(PartnerLocationsDS, APartnerKey, ATransaction);

            Calculations.DeterminePartnerLocationsDateStatus(PartnerLocationsDS);
            Calculations.DetermineBestAddress(PartnerLocationsDS);

            foreach (PPartnerLocationRow row in PartnerLocationTable.Rows)
            {
                if (AOnlySendMail && !Convert.ToBoolean(row[PPartnerLocationTable.GetSendMailDBName()]))
                {
                    // ignore addresses that are not set for receiving mail.
                    continue;
                }

                // find the row with BestAddress = 1
                if (Convert.ToInt32(row["BestAddress"]) == 1)
                {
                    // we also want the post address, need to load the p_location table:
                    AAddress = PLocationAccess.LoadByPrimaryKey(row.SiteKey, row.LocationKey, ATransaction);

                    // watch out for empty country codes
                    if (AAddress[0].CountryCode.Trim().Length > 0)
                    {
                        if (CountryTable.DefaultView.Find(AAddress[0].CountryCode) == -1)
                        {
                            CountryTable.Merge(PCountryAccess.LoadByPrimaryKey(AAddress[0].CountryCode, ATransaction));
                        }

                        ACountryNameLocal = CountryTable[CountryTable.DefaultView.Find(AAddress[0].CountryCode)].CountryNameLocal;
                    }

                    break;
                }
            }

            return(AAddress != null);
        }
Exemple #8
0
 /// <summary>
 /// Update extra location specific fields in table APartnerLocationTable
 /// </summary>
 /// <param name="ALocationDT">Table containing location records to be used to update APartnerLocation records.</param>
 /// <param name="APartnerLocationDT">Table to be updated with Location specific information.</param>
 /// <param name="AMakePLocationRecordUnchanged">Set to true to make the PLocation Record unchanged
 /// (by calling .AcceptChanges() on it).</param>
 public static void SyncPartnerEditTDSPartnerLocation(PLocationTable ALocationDT, PartnerEditTDSPPartnerLocationTable APartnerLocationDT,
                                                      bool AMakePLocationRecordUnchanged = false)
 {
     foreach (PartnerEditTDSPPartnerLocationRow PartnerLocationRow in APartnerLocationDT.Rows)
     {
         SyncPartnerEditTDSPartnerLocation(ALocationDT, PartnerLocationRow, AMakePLocationRecordUnchanged);
     }
 }
Exemple #9
0
 /// <summary>
 /// Creates a new DataRow in the passed PLocation and PPartnerLocation tables.
 ///
 /// </summary>
 /// <param name="ALocationDT">Typed PLocation table. If nil is passed in it is created
 /// automatically</param>
 /// <param name="APartnerLocationDT">Typed PPartnerLocation table. If nil is passed in
 /// it is created automatically</param>
 /// <param name="APartnerKey">PartneKey of the Partner for which the Address should
 /// be created</param>
 /// <param name="APartnerClass">PartnerClass of the Partner for which the Address should
 /// be created</param>
 /// <param name="ACountryCode"></param>
 /// <param name="ANewLocationKey">A LocationKey that the new Location and
 /// PartnerLocation rows would be set to.</param>
 /// <returns>void</returns>
 /// <exception cref="ArgumentException"> if any of the Arguments (or their combination) is
 /// not valid
 /// </exception>
 public static void CreateNewAddress(PLocationTable ALocationDT,
                                     PPartnerLocationTable APartnerLocationDT,
                                     Int64 APartnerKey,
                                     TPartnerClass APartnerClass,
                                     String ACountryCode,
                                     Int32 ANewLocationKey)
 {
     CreateNewAddressInternal(ALocationDT, APartnerLocationDT, APartnerKey, APartnerClass, ACountryCode, ANewLocationKey);
 }
 /// <summary>
 /// Creates a new DataRow in the passed PLocation and PPartnerLocation tables.
 ///
 /// </summary>
 /// <param name="ALocationDT">Typed PLocation table. If nil is passed in it is created
 /// automatically</param>
 /// <param name="APartnerLocationDT">Typed PPartnerLocation table. If nil is passed in
 /// it is created automatically</param>
 /// <param name="APartnerKey">PartneKey of the Partner for which the Address should
 /// be created</param>
 /// <param name="APartnerClass">PartnerClass of the Partner for which the Address should
 /// be created</param>
 /// <param name="ACountryCode"></param>
 /// <param name="ANewLocationKey">A LocationKey that the new Location and
 /// PartnerLocation rows would be set to.</param>
 /// <returns>void</returns>
 /// <exception cref="ArgumentException"> if any of the Arguments (or their combination) is
 /// not valid
 /// </exception>
 public static void CreateNewAddress(PLocationTable ALocationDT,
     PPartnerLocationTable APartnerLocationDT,
     Int64 APartnerKey,
     TPartnerClass APartnerClass,
     String ACountryCode,
     Int32 ANewLocationKey)
 {
     CreateNewAddressInternal(ALocationDT, APartnerLocationDT, APartnerKey, APartnerClass, ACountryCode, ANewLocationKey);
 }
Exemple #11
0
 /// find the current best address for the partner, only return address with sendmail set.
 public static bool GetBestAddressOnlySendMail(Int64 APartnerKey,
                                               out PLocationTable AAddress,
                                               out string ACountryNameLocal,
                                               TDBTransaction ATransaction)
 {
     return(GetBestAddress(APartnerKey,
                           out AAddress, out ACountryNameLocal,
                           ATransaction, true));
 }
Exemple #12
0
        /// <summary>
        /// get the best email address that is valid today, with some location details
        /// </summary>
        public static string GetBestEmailAddressWithDetails(Int64 APartnerKey, out PLocationTable AAddress, out string ACountryNameLocal)
        {
            string         EmailAddress     = "";
            PLocationTable Address          = null;
            string         CountryNameLocal = "";
            TDBTransaction Transaction      = null;

            DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted, ref Transaction,
                                                                      delegate
            {
                DataSet PartnerLocationsDS = new DataSet();

                PartnerLocationsDS.Tables.Add(new PPartnerLocationTable());
                PartnerLocationsDS.Tables.Add(new PCountryTable());
                DataTable PartnerLocationTable = PartnerLocationsDS.Tables[PPartnerLocationTable.GetTableName()];
                PCountryTable CountryTable     = (PCountryTable)PartnerLocationsDS.Tables[PCountryTable.GetTableName()];
                CountryTable.DefaultView.Sort  = PCountryTable.GetCountryCodeDBName();

                // add special column BestAddress and Icon
                PartnerLocationTable.Columns.Add(new System.Data.DataColumn("BestAddress", typeof(Boolean)));
                PartnerLocationTable.Columns.Add(new System.Data.DataColumn("Icon", typeof(Int32)));

                // find all locations of the partner, put it into a dataset
                PPartnerLocationAccess.LoadViaPPartner(PartnerLocationsDS, APartnerKey, Transaction);

                Ict.Petra.Shared.MPartner.Calculations.DeterminePartnerLocationsDateStatus(PartnerLocationsDS);
                Ict.Petra.Shared.MPartner.Calculations.DetermineBestAddress(PartnerLocationsDS);

                foreach (PPartnerLocationRow row in PartnerLocationTable.Rows)
                {
                    // find the row with BestAddress = 1
                    if (Convert.ToInt32(row["BestAddress"]) == 1)
                    {
                        if (!row.IsEmailAddressNull())
                        {
                            EmailAddress = row.EmailAddress;
                        }

                        // we also want the post address, need to load the p_location table:
                        Address = PLocationAccess.LoadByPrimaryKey(row.SiteKey, row.LocationKey, Transaction);

                        if (CountryTable.DefaultView.Find(Address[0].CountryCode) == -1)
                        {
                            CountryTable.Merge(PCountryAccess.LoadByPrimaryKey(Address[0].CountryCode, Transaction));
                        }

                        CountryNameLocal = CountryTable[CountryTable.DefaultView.Find(Address[0].CountryCode)].CountryNameLocal;
                    }
                }
            });

            AAddress          = Address;
            ACountryNameLocal = CountryNameLocal;

            return(EmailAddress);
        }
        /// <summary>
        /// Populates the grid for the dialog for selecting Addresses to be merged.
        /// </summary>
        public bool InitializeAddressGrid(long APartnerKey)
        {
            // set text for label
            lblInfo.Text = Catalog.GetString("The following addresses exist for the Partner being merged. Select the addresses to be transferred.") +
                           "\n\n" + Catalog.GetString("Any addresses which are not selected will be deleted!");

            string CheckedMember = "CHECKED";
            string Address1      = PLocationTable.GetLocalityDBName();
            string Street2       = PLocationTable.GetStreetNameDBName();
            string Address3      = PLocationTable.GetAddress3DBName();
            string City          = PLocationTable.GetCityDBName();
            string LocationKey   = PLocationTable.GetLocationKeyDBName();
            string SiteKey       = PLocationTable.GetSiteKeyDBName();
            string LocationType  = PPartnerLocationTable.GetLocationTypeDBName();


            FMainDS = TRemote.MPartner.Partner.WebConnectors.GetPartnerDetails(APartnerKey, true, false, false);

            if ((FMainDS != null) && (FMainDS.PLocation != null) && (FMainDS.PLocation.Rows.Count > 0))
            {
                DataView MyDataView = FMainDS.PLocation.DefaultView;

                FDataTable = MyDataView.ToTable(true, new string[] { Address1, Street2, Address3, City, LocationKey, SiteKey });
                FDataTable.Columns.Add(new DataColumn(CheckedMember, typeof(bool)));
                FDataTable.Columns.Add(LocationType, typeof(string));

                for (int Counter = 0; Counter < FMainDS.PLocation.Rows.Count; ++Counter)
                {
                    FDataTable.Rows[Counter][LocationType] = FMainDS.PPartnerLocation.Rows[Counter][LocationType];
                }

                clbRecords.Columns.Clear();
                clbRecords.AddCheckBoxColumn("", FDataTable.Columns[CheckedMember], 17, false);
                clbRecords.AddTextColumn("Address-1", FDataTable.Columns[Address1]);
                clbRecords.AddTextColumn("Street-2", FDataTable.Columns[Street2]);
                clbRecords.AddTextColumn("Address-3", FDataTable.Columns[Address3]);
                clbRecords.AddTextColumn("City", FDataTable.Columns[City]);
                clbRecords.AddTextColumn("Location Type", FDataTable.Columns[LocationType]);
                clbRecords.ValueChanged += new EventHandler(OnCheckboxChange);

                clbRecords.DataBindGrid(FDataTable, Address1, CheckedMember, Address1, false, true, false);
                clbRecords.SetCheckedStringList("");

                clbRecords.AutoResizeGrid();

                return(true);
            }
            else
            {
                return(false);
            }
        }
Exemple #14
0
 private DataTable GetCountryListFromExistingLocationsTable(TDBTransaction AReadTransaction, string ATableName)
 {
     // Used eg. in Report Gift Data Export for finding donors.
     return(DBAccess.GDBAccessObj.SelectDT("SELECT DISTINCT " + "PUB." + PCountryTable.GetTableDBName() + '.' +
                                           PCountryTable.GetCountryCodeDBName() + ", " +
                                           PCountryTable.GetCountryNameDBName() + " FROM PUB." +
                                           PCountryTable.GetTableDBName() + " c, PUB." +
                                           PLocationTable.GetTableDBName() + " l " +
                                           " WHERE " + PLocationTable.GetCountyDBName() + " IS NOT NULL AND NOT " +
                                           PLocationTable.GetCountyDBName() + " = ''" +
                                           " AND c." + PCountryTable.GetCountryCodeDBName() + " = l." +
                                           PLocationTable.GetCountryCodeDBName(), ATableName, AReadTransaction));
 }
Exemple #15
0
        /// find the current best address for the partner
        public static bool GetBestAddress(Int64 APartnerKey,
            out PLocationTable AAddress,
            out string ACountryNameLocal,
            TDBTransaction ATransaction)
        {
            AAddress = null;
            ACountryNameLocal = "";

            DataSet PartnerLocationsDS = new DataSet();

            PartnerLocationsDS.Tables.Add(new PPartnerLocationTable());
            PartnerLocationsDS.Tables.Add(new PCountryTable());
            DataTable PartnerLocationTable = PartnerLocationsDS.Tables[PPartnerLocationTable.GetTableName()];
            PCountryTable CountryTable = (PCountryTable)PartnerLocationsDS.Tables[PCountryTable.GetTableName()];
            CountryTable.DefaultView.Sort = PCountryTable.GetCountryCodeDBName();

            // add special column BestAddress and Icon
            PartnerLocationTable.Columns.Add(new System.Data.DataColumn("BestAddress", typeof(Boolean)));
            PartnerLocationTable.Columns.Add(new System.Data.DataColumn("Icon", typeof(Int32)));

            // find all locations of the partner, put it into a dataset
            PPartnerLocationAccess.LoadViaPPartner(PartnerLocationsDS, APartnerKey, ATransaction);

            Ict.Petra.Shared.MPartner.Calculations.DeterminePartnerLocationsDateStatus(PartnerLocationsDS);
            Ict.Petra.Shared.MPartner.Calculations.DetermineBestAddress(PartnerLocationsDS);

            foreach (PPartnerLocationRow row in PartnerLocationTable.Rows)
            {
                // find the row with BestAddress = 1
                if (Convert.ToInt32(row["BestAddress"]) == 1)
                {
                    // we also want the post address, need to load the p_location table:
                    AAddress = PLocationAccess.LoadByPrimaryKey(row.SiteKey, row.LocationKey, ATransaction);

                    // watch out for empty country codes
                    if (AAddress[0].CountryCode.Trim().Length > 0)
                    {
                        if (CountryTable.DefaultView.Find(AAddress[0].CountryCode) == -1)
                        {
                            CountryTable.Merge(PCountryAccess.LoadByPrimaryKey(AAddress[0].CountryCode, ATransaction));
                        }

                        ACountryNameLocal = CountryTable[CountryTable.DefaultView.Find(AAddress[0].CountryCode)].CountryNameLocal;
                    }

                    break;
                }
            }

            return AAddress != null;
        }
        private DataTable GetConferenceListTable(TDBTransaction AReadTransaction, string ATableName)
        {
            DataTable Table;

            DataColumn[] Key = new DataColumn[1];

            // Used eg. Select Event Dialog
            Table = DBAccess.GetDBAccessObj(AReadTransaction).SelectDT(
                "SELECT DISTINCT " +
                PPartnerTable.GetPartnerShortNameDBName() +
                ", " + PPartnerTable.GetPartnerClassDBName() +
                ", " + PUnitTable.GetOutreachCodeDBName() +
                ", " + PCountryTable.GetTableDBName() + "." + PCountryTable.GetCountryNameDBName() +
                ", " + PPartnerLocationTable.GetTableDBName() + "." + PPartnerLocationTable.GetDateEffectiveDBName() +
                ", " + PPartnerLocationTable.GetTableDBName() + "." + PPartnerLocationTable.GetDateGoodUntilDBName() +
                ", " + PPartnerTable.GetTableDBName() + "." + PPartnerTable.GetPartnerKeyDBName() +
                ", " + PUnitTable.GetUnitTypeCodeDBName() +

                " FROM PUB." + PPartnerTable.GetTableDBName() +
                ", PUB." + PUnitTable.GetTableDBName() +
                ", PUB." + PLocationTable.GetTableDBName() +
                ", PUB." + PPartnerLocationTable.GetTableDBName() +
                ", PUB." + PCountryTable.GetTableDBName() +

                " WHERE " +
                PPartnerTable.GetTableDBName() + "." + PPartnerTable.GetPartnerKeyDBName() + " = " +
                PUnitTable.GetTableDBName() + "." + PUnitTable.GetPartnerKeyDBName() + " AND " +
                PPartnerTable.GetTableDBName() + "." + PPartnerTable.GetPartnerKeyDBName() + " = " +
                PPartnerLocationTable.GetTableDBName() + "." + PPartnerLocationTable.GetPartnerKeyDBName() + " AND " +

                PLocationTable.GetTableDBName() + "." + PLocationTable.GetSiteKeyDBName() + " = " +
                PPartnerLocationTable.GetTableDBName() + "." + PPartnerLocationTable.GetSiteKeyDBName() + " AND " +
                PLocationTable.GetTableDBName() + "." + PLocationTable.GetLocationKeyDBName() + " = " +
                PPartnerLocationTable.GetTableDBName() + "." + PPartnerLocationTable.GetLocationKeyDBName() + " AND " +
                PCountryTable.GetTableDBName() + "." + PCountryTable.GetCountryCodeDBName() + " = " +
                PLocationTable.GetTableDBName() + "." + PLocationTable.GetCountryCodeDBName() + " AND " +


                PPartnerTable.GetStatusCodeDBName() + " = 'ACTIVE' AND " +
                PPartnerTable.GetPartnerClassDBName() + " = 'UNIT' AND (" +
                PUnitTable.GetUnitTypeCodeDBName() + " LIKE '%CONF%' OR " +
                PUnitTable.GetUnitTypeCodeDBName() + " LIKE '%CONG%')"
                ,
                ATableName, AReadTransaction);

            Key[0]           = Table.Columns[PPartnerTable.GetPartnerKeyDBName()];
            Table.PrimaryKey = Key;

            return(Table);
        }
        /// <summary>
        /// Returns the SiteKeys for all the rows selected in the grid.
        /// </summary>
        public long[] GetSelectedSiteKeys()
        {
            long[] SiteKeys = new long[clbRecords.CheckedItemsCount];
            int    i        = 0;

            foreach (DataRow Row in FDataTable.Rows)
            {
                if (Convert.ToBoolean(Row["Checked"]) == true)
                {
                    SiteKeys[i] = Convert.ToInt64(Row[PLocationTable.GetSiteKeyDBName()]);
                    i++;
                }
            }

            return(SiteKeys);
        }
        /// <summary>
        /// Returns the LocationKeys for all the rows selected in the grid.
        /// </summary>
        public int[] GetSelectedLocationKeys()
        {
            int[] LocationKeys = new int[clbRecords.CheckedItemsCount];
            int   i            = 0;

            foreach (DataRow Row in FDataTable.Rows)
            {
                if (Convert.ToBoolean(Row["Checked"]) == true)
                {
                    LocationKeys[i] = Convert.ToInt32(Row[PLocationTable.GetLocationKeyDBName()]);
                    i++;
                }
            }

            return(LocationKeys);
        }
        /// <summary>
        /// Private method used by ExportPartners().
        /// For the given partnerKey, updates given references countryCode and siteKey.
        /// If there is no location for the given partnerKey, leaves them as they are.
        /// </summary>
        /// <param name="MainDS">Reference to the already filled Datastructure</param>
        /// <param name="partnerKey"></param>
        /// <param name="countryCode"></param>
        /// <param name="siteKey"></param>
        /// <returns>
        /// True: if a location was found for given key and the countryCode
        /// and siteKey were updated. False otherwise.
        /// </returns>
        private static bool UpdateCountryAndSiteForGivenPK(
            PartnerEditTDS MainDS,
            long partnerKey,
            ref string countryCode /* default could be "" */,
            ref Int64 siteKey /* default could be -1 */
            )
        {
            bool retval = false;
            // Find partnerLocation for given partner_key
            DataView partnerLocationView = MainDS.PPartnerLocation.DefaultView;

            partnerLocationView.RowFilter = PPartnerLocationTable.GetPartnerKeyDBName() + " = " + partnerKey.ToString();

            if (partnerLocationView.Count > 0)
            {
                // partnerLocation: links one partner to possibly several Locations
                // Just get the first one for now (and disregard the others).
                // TODO: could determine the best address and use that
                PPartnerLocationRow partnerLocationRow = (PPartnerLocationRow)partnerLocationView[0].Row;

                DataView locationView = MainDS.PLocation.DefaultView;
                locationView.RowFilter =
                    PLocationTable.GetSiteKeyDBName() + "=" + partnerLocationRow.SiteKey.ToString() + " AND " +
                    PLocationTable.GetLocationKeyDBName() + "=" + partnerLocationRow.LocationKey.ToString();

                if (locationView.Count > 0)
                {
                    PLocationRow locationRow = (PLocationRow)locationView[0].Row;
                    countryCode = locationRow.CountryCode;
                    siteKey     = locationRow.SiteKey;
                    retval      = true;
                }
                else     // if there is a partner_location, there has _got_ to be the corresponding location
                {
                    throw new Exception("Error in application: I can't find the Location with LocationKey " +
                                        partnerLocationRow.LocationKey.ToString() +
                                        " (Sitekey " + partnerLocationRow.SiteKey.ToString() + ")"
                                        );
                }
            }

            return(retval);
        }
Exemple #20
0
        /// <summary>
        /// Update extra location specific fields in DataRow APartnerLocationDR
        /// </summary>
        /// <param name="ALocationDT">Table containing location records to be used to update APartnerLocation records.</param>
        /// <param name="APartnerLocationDR">Single DataRow to be updated with Location specific information.</param>
        /// <param name="AMakePLocationRecordUnchanged">Set to true to make the PLocation Record unchanged
        /// (by calling .AcceptChanges() on it).</param>
        public static void SyncPartnerEditTDSPartnerLocation(PLocationTable ALocationDT, PartnerEditTDSPPartnerLocationRow APartnerLocationDR,
                                                             bool AMakePLocationRecordUnchanged = false)
        {
            DataRow      Row;
            PLocationRow LocationRow;

            if (APartnerLocationDR.RowState != DataRowState.Deleted)
            {
                Row = ALocationDT.Rows.Find(new Object[] { APartnerLocationDR.SiteKey, APartnerLocationDR.LocationKey });

                if (Row != null)
                {
                    LocationRow = (PLocationRow)Row;

                    APartnerLocationDR.LocationLocality    = LocationRow.Locality;
                    APartnerLocationDR.LocationStreetName  = LocationRow.StreetName;
                    APartnerLocationDR.LocationAddress3    = LocationRow.Address3;
                    APartnerLocationDR.LocationCity        = LocationRow.City;
                    APartnerLocationDR.LocationCounty      = LocationRow.County;
                    APartnerLocationDR.LocationPostalCode  = LocationRow.PostalCode;
                    APartnerLocationDR.LocationCountryCode = LocationRow.CountryCode;

                    APartnerLocationDR.LocationCreatedBy = LocationRow.CreatedBy;

                    if (!LocationRow.IsDateCreatedNull())
                    {
                        APartnerLocationDR.LocationDateCreated = (DateTime)LocationRow.DateCreated;
                    }

                    APartnerLocationDR.LocationModifiedBy = LocationRow.ModifiedBy;

                    if (!LocationRow.IsDateModifiedNull())
                    {
                        APartnerLocationDR.LocationDateModified = (DateTime)LocationRow.DateModified;
                    }

                    if (AMakePLocationRecordUnchanged)
                    {
                        Row.AcceptChanges();
                    }
                }
            }
        }
Exemple #21
0
        /// <summary>
        /// Update extra location specific fields in table APartnerLocationTable
        /// </summary>
        /// <param name="ALocationTable">Table containing location records to be used to update APartnerLocation records</param>
        /// <param name="APartnerLocationTable">Table to be updated with Location specific information</param>
        /// <returns></returns>
        public static void SyncPartnerEditTDSPartnerLocation(PLocationTable ALocationTable, PartnerEditTDSPPartnerLocationTable APartnerLocationTable)
        {
            DataRow Row;
            PLocationRow LocationRow;

            foreach (PartnerEditTDSPPartnerLocationRow PartnerLocationRow in APartnerLocationTable.Rows)
            {
                Row = ALocationTable.Rows.Find(new Object[] { PartnerLocationRow.SiteKey, PartnerLocationRow.LocationKey });

                if (Row != null)
                {
                    LocationRow = (PLocationRow)Row;

                    PartnerLocationRow.LocationLocality = LocationRow.Locality;
                    PartnerLocationRow.LocationStreetName = LocationRow.StreetName;
                    PartnerLocationRow.LocationAddress3 = LocationRow.Address3;
                    PartnerLocationRow.LocationCity = LocationRow.City;
                    PartnerLocationRow.LocationCounty = LocationRow.County;
                    PartnerLocationRow.LocationPostalCode = LocationRow.PostalCode;
                    PartnerLocationRow.LocationCountryCode = LocationRow.CountryCode;

                    PartnerLocationRow.LocationCreatedBy = LocationRow.CreatedBy;

                    if (!LocationRow.IsDateCreatedNull())
                    {
                        PartnerLocationRow.LocationDateCreated = (DateTime)LocationRow.DateCreated;
                    }

                    PartnerLocationRow.LocationModifiedBy = LocationRow.ModifiedBy;

                    if (!LocationRow.IsDateModifiedNull())
                    {
                        PartnerLocationRow.LocationDateModified = (DateTime)LocationRow.DateModified;
                    }
                }
            }
        }
Exemple #22
0
        /// <summary>
        /// Update extra location specific fields in table APartnerLocationTable
        /// </summary>
        /// <param name="ALocationTable">Table containing location records to be used to update APartnerLocation records</param>
        /// <param name="APartnerLocationTable">Table to be updated with Location specific information</param>
        /// <returns></returns>
        public static void SyncPartnerEditTDSPartnerLocation(PLocationTable ALocationTable, PartnerEditTDSPPartnerLocationTable APartnerLocationTable)
        {
            DataRow      Row;
            PLocationRow LocationRow;

            foreach (PartnerEditTDSPPartnerLocationRow PartnerLocationRow in APartnerLocationTable.Rows)
            {
                Row = ALocationTable.Rows.Find(new Object[] { PartnerLocationRow.SiteKey, PartnerLocationRow.LocationKey });

                if (Row != null)
                {
                    LocationRow = (PLocationRow)Row;

                    PartnerLocationRow.LocationLocality    = LocationRow.Locality;
                    PartnerLocationRow.LocationStreetName  = LocationRow.StreetName;
                    PartnerLocationRow.LocationAddress3    = LocationRow.Address3;
                    PartnerLocationRow.LocationCity        = LocationRow.City;
                    PartnerLocationRow.LocationCounty      = LocationRow.County;
                    PartnerLocationRow.LocationPostalCode  = LocationRow.PostalCode;
                    PartnerLocationRow.LocationCountryCode = LocationRow.CountryCode;

                    PartnerLocationRow.LocationCreatedBy = LocationRow.CreatedBy;

                    if (!LocationRow.IsDateCreatedNull())
                    {
                        PartnerLocationRow.LocationDateCreated = (DateTime)LocationRow.DateCreated;
                    }

                    PartnerLocationRow.LocationModifiedBy = LocationRow.ModifiedBy;

                    if (!LocationRow.IsDateModifiedNull())
                    {
                        PartnerLocationRow.LocationDateModified = (DateTime)LocationRow.DateModified;
                    }
                }
            }
        }
Exemple #23
0
 /// <summary>
 /// Creates a new DataRow in the passed PLocation and PPartnerLocation tables.
 /// </summary>
 /// <param name="ALocationDT">Typed PLocation table. If null is passed in it is created
 /// automatically</param>
 /// <param name="APartnerLocationDT">Typed PPartnerLocation table. If null is passed in
 /// it is created automatically</param>
 /// <param name="APartnerKey">PartneKey of the Partner for which the Address should
 /// be created</param>
 /// <param name="APartnerClass">PartnerClass of the Partner for which the Address should
 /// be created</param>
 /// <param name="ACountryCode"></param>
 /// <param name="ANewLocationKey">A LocationKey that the new Location and
 /// PartnerLocation rows would be set to.</param>
 /// <param name="ACopyFromFamilyPartnerKey">Pass in the PartnerKey of a Family Partner
 /// to copy over all data from the Family's Address. Note: the DataRow
 /// specified with ACopyFromFamilyPartnerKey must be present in the
 /// APartnerLocationDT table!</param>
 /// <param name="ACopyFromFamilyLocationKey">Pass in the LocationKey of the Family
 /// Partner specified in ACopyFromFamilyPartnerKey to copy over all data from
 /// the Family's Address. Note: the DataRow specified with
 /// ACopyFromFamilyLocationKey must be present in both the ALocationDT and
 /// APartnerLocationDT table!</param>
 /// <param name="ACopyFromFamilySiteKey">A SiteKey to find the location that should be the source of the copy</param>
 /// <param name="ACopyFromFamilyOnlyLocation"></param>
 /// <param name="ADeleteDataRowCopiedFrom"></param>
 /// <exception cref="ArgumentException"> if any of the Arguments (or their combination) is
 /// not valid.</exception>
 public static void CreateNewAddress(PLocationTable ALocationDT,
                                     PPartnerLocationTable APartnerLocationDT,
                                     Int64 APartnerKey,
                                     TPartnerClass APartnerClass,
                                     String ACountryCode,
                                     Int32 ANewLocationKey,
                                     Int64 ACopyFromFamilyPartnerKey,
                                     Int32 ACopyFromFamilyLocationKey,
                                     Int64 ACopyFromFamilySiteKey,
                                     Boolean ACopyFromFamilyOnlyLocation,
                                     Boolean ADeleteDataRowCopiedFrom)
 {
     CreateNewAddressInternal(ALocationDT,
                              APartnerLocationDT,
                              APartnerKey,
                              APartnerClass,
                              ACountryCode,
                              ANewLocationKey,
                              ACopyFromFamilyPartnerKey,
                              ACopyFromFamilyLocationKey,
                              ACopyFromFamilySiteKey,
                              ACopyFromFamilyOnlyLocation,
                              ADeleteDataRowCopiedFrom);
 }
Exemple #24
0
        /// <summary>
        /// Returns the PLocationRow of the 'Best Address'.
        /// </summary>
        /// <remarks>One of the 'DetermineBestAddress' Methods must have been run before on the PartnerLocation
        /// Table that gets passed in in the <paramref name="APartnerLocationDT" /> Argument!!!</remarks>
        /// <param name="APartnerLocationDT">Typed PartnerLocation Table that was already processed by one of the
        /// 'DetermineBestAddress' Methods.</param>
        /// <param name="ALocationDT">Location Table that contains all Location records that are referenced in
        /// <paramref name="APartnerLocationDT" />.</param>
        /// <returns>Location Row of the 'Best Address'.</returns>
        public static PLocationRow FindBestAddressLocation(PartnerEditTDSPPartnerLocationTable APartnerLocationDT,
                                                           PLocationTable ALocationDT)
        {
            PartnerEditTDSPPartnerLocationRow CheckDR;
            string       NameOfBestAddrColumn = PartnerEditTDSPPartnerLocationTable.GetBestAddressDBName();
            var          BestLocationPK       = new TLocationPK(-1, -1);
            PLocationRow BestLocationDR;

            for (int Counter = 0; Counter < APartnerLocationDT.Count; Counter++)
            {
                CheckDR = APartnerLocationDT[Counter];

                if (CheckDR[NameOfBestAddrColumn] == ((object)1))
                {
                    BestLocationPK = new TLocationPK(CheckDR.SiteKey, CheckDR.LocationKey);
                }
            }

            if ((BestLocationPK.SiteKey == -1) &&
                (BestLocationPK.LocationKey == -1))
            {
                throw new EOPAppException(
                          "FindBestAddressLocation Method was unable to determine the 'Best Address' (PPartnerLocation error)! (Was 'DetermineBestAddress' run before?)");
            }

            BestLocationDR = (PLocationRow)ALocationDT.Rows.Find(
                new object[] { BestLocationPK.SiteKey, BestLocationPK.LocationKey });

            if (BestLocationDR == null)
            {
                throw new EOPAppException(
                          "FindBestAddressLocation Method was unable to determine the 'Best Address' (PLocation error)! (Was 'DetermineBestAddress' run before?)");
            }

            return(BestLocationDR);
        }
Exemple #25
0
        private void CreateColumns()
        {
            string Tmp;
            string LocalisedCountyLabel;

            LocalisedStrings.GetLocStrCounty(out LocalisedCountyLabel, out Tmp);

            // Done this way in case it changes
            LocalisedCountyLabel = LocalisedCountyLabel.Replace(":", "").Replace("&", "");

            grdResult.Columns.Clear();

            grdResult.AddTextColumn("City", FPagedDataTable.Columns[PLocationTable.GetCityDBName()]);
            grdResult.AddTextColumn("Post Code", FPagedDataTable.Columns[PLocationTable.GetPostalCodeDBName()]);
            grdResult.AddTextColumn("Addr1", FPagedDataTable.Columns[PLocationTable.GetLocalityDBName()]);
            grdResult.AddTextColumn("Street-2", FPagedDataTable.Columns[PLocationTable.GetStreetNameDBName()]);
            grdResult.AddTextColumn("Addr3", FPagedDataTable.Columns[PLocationTable.GetAddress3DBName()]);
            grdResult.AddTextColumn(LocalisedCountyLabel, FPagedDataTable.Columns[PLocationTable.GetCountyDBName()]);
            grdResult.AddTextColumn("Country", FPagedDataTable.Columns[PLocationTable.GetCountryCodeDBName()]);
            grdResult.AddTextColumn("Location Key", FPagedDataTable.Columns[PLocationTable.GetLocationKeyDBName()]);
            grdResult.AddTextColumn("SiteKey", FPagedDataTable.Columns[PLocationTable.GetSiteKeyDBName()]);

            grdResult.AutoResizeGrid();
        }
Exemple #26
0
        /// <summary>
        /// Run the queries and check the results
        /// </summary>
        /// <param name="StreetLine"></param>
        public void ActAndAssert(string StreetLine)
        {
            string         ACountryName;
            PLocationTable AAddress       = null;
            TDBTransaction ATransaction   = null;
            DataTable      DonorAddresses = null;

            // Act
            DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted, TEnforceIsolationLevel.eilMinimum,
                                                                      ref ATransaction,
                                                                      delegate
            {
                TAddressTools.GetBestAddress(TestPartnerKey, out AAddress, out ACountryName, ATransaction);
                DonorAddresses = TAddressTools.GetBestAddressForPartners(TestPartnerKey.ToString(), ATransaction);
            });

            // Assert
            Assert.AreEqual(1, AAddress.Rows.Count, "GetBestAddress returned wrong number of addresses");
            Assert.AreEqual(1, DonorAddresses.Rows.Count, "GetBestAddressForPartners returned wrong number of addresses");
            Assert.AreEqual(TestPartnerKey + " " + StreetLine,
                            ((PLocationRow)AAddress.Rows[0]).StreetName,
                            "GetBestAddress returned unexpected address");
            Assert.AreEqual(((PLocationRow)AAddress.Rows[0]).LocationKey, DonorAddresses.Rows[0]["p_location_key_i"]);
        }
        /// <summary>
        /// Check each Location DataRow before calling SubmitChanges
        /// to enforce Business Rules:
        /// - Added or changed Location: check for a similar Location record
        /// - if no similar Location record exists, save this Location record
        /// - if a similar Location record exists: allow choosing whether the
        ///    existing one should be used, or this Location record should be saved
        /// - Changed Location: don't save Location record if the data is actually
        ///     the same than before
        /// - Deleted Location: delete Location only if no other PartnerLocation
        ///      is referencing it
        /// - Deleted Location: remove references from any Extracts
        /// </summary>
        private static TSubmitChangesResult ProcessLocationChanges(
            PLocationTable ALocationTable,
            PPartnerLocationTable APartnerLocationTable,
            ref PartnerAddressAggregateTDS AResponseDS,
            TDBTransaction ASubmitChangesTransaction,
            Int64 APartnerKey,
            ref PartnerAddressAggregateTDSSimilarLocationParametersTable AExistingLocationParametersDT,
            ref TLocationPK[, ] ASimilarLocationReUseKeyMapping,
            ref PartnerAddressAggregateTDSAddressAddedOrChangedPromotionTable AAddressAddedOrChangedPromotionParametersDT,
            ref PartnerAddressAggregateTDSChangePromotionParametersTable AChangeLocationParametersDT,
            ref TVerificationResultCollection AVerificationResult)
        {
            TSubmitChangesResult Result = TSubmitChangesResult.scrOK;
            TSubmitChangesResult TmpResult;

            for (Int16 LocationCounter = 0; LocationCounter < ALocationTable.Rows.Count; LocationCounter++)
            {
                if ((ALocationTable.Rows[LocationCounter].RowState == DataRowState.Added)
                    || (ALocationTable.Rows[LocationCounter].RowState == DataRowState.Modified))
                {
                    if (ALocationTable[LocationCounter].LocationKey == 0)
                    {
                        throw new Exception("TPPartnerAddress.ProcessLocationChanges: must not add or modify the empty location");
                    }
                }

                if (ALocationTable.Rows[LocationCounter].RowState == DataRowState.Deleted)
                {
                    if (Convert.ToInt32(ALocationTable[LocationCounter][PLocationTable.GetLocationKeyDBName(),
                                                                        DataRowVersion.Original]) == 0)
                    {
                        throw new Exception("TPPartnerAddress.ProcessLocationChanges: must not delete the empty location");
                    }
                }

                if (ALocationTable.Rows[LocationCounter].RowState == DataRowState.Added)
                {
                    bool ReUseSimilarLocation = false;

                    // Check for reuse of a similar location in the DB
                    PLocationRow TmpRow = ALocationTable[LocationCounter];
                    TmpResult = PerformSimilarLocationReUseChecks(
                        ref TmpRow,
                        ref AResponseDS,
                        ASubmitChangesTransaction,
                        APartnerKey,
                        ref AExistingLocationParametersDT,
                        ref APartnerLocationTable,
                        ref ASimilarLocationReUseKeyMapping,
                        out ReUseSimilarLocation,
                        ref AVerificationResult);
//                  TLogging.LogAtLevel(8, "SubmitChanges: TmpRow.LocationKey after PerformSimilarLocationReUseChecks (1): " + TmpRow.LocationKey.ToString());

                    if (TmpResult != TSubmitChangesResult.scrOK)
                    {
                        // Stop processing here - we need a decision whether to re-use
                        // an existing Location or not (or the user tried to re-use a
                        // Location that is already used by this Partner, which is a
                        // user error)
                        return TmpResult;
                    }
                } // DataRowState.Added
                else if (ALocationTable.Rows[LocationCounter].RowState == DataRowState.Modified)
                {
                    if (CheckHasLocationChanged(ALocationTable[LocationCounter]))
                    {
                        bool ReUseSimilarLocation = false;

                        // Check for reuse of a similar location in the DB
                        PLocationRow TmpRow = ALocationTable[LocationCounter];
                        TmpResult = PerformSimilarLocationReUseChecks(ref TmpRow,
                            ref AResponseDS,
                            ASubmitChangesTransaction,
                            APartnerKey,
                            ref AExistingLocationParametersDT,
                            ref APartnerLocationTable,
                            ref ASimilarLocationReUseKeyMapping,
                            out ReUseSimilarLocation,
                            ref AVerificationResult);

//                      TLogging.LogAtLevel(9, "SubmitChanges: TmpRow.LocationKey after PerformSimilarLocationReUseChecks (2): " + TmpRow.LocationKey.ToString());

                        if (TmpResult != TSubmitChangesResult.scrOK)
                        {
                            // Stop processing here - we need a decision whether to re-use
                            // an existing Location or not (or the user tried to re-use a
                            // Location that is already used by this Partner, which is a
                            // user error)
                            return TmpResult;
                        }

                        if (!ReUseSimilarLocation)
                        {
                            // No similar Location exists, or an existing similar Location
                            // should not be reused
                            if (CheckHasPartnerLocationOtherPartnerReferences(ALocationTable[LocationCounter], APartnerKey,
                                    ASubmitChangesTransaction))
                            {
//                              TLogging.LogAtLevel(9, "SubmitChanges: Location " + ALocationTable[LocationCounter].LocationKey.ToString() + ": is used by other Partners as well.");

                                bool CreateLocationFlag;
                                TLocationPK OriginalLocationKey;

                                TmpResult =
                                    PerformLocationChangeChecks(ALocationTable[LocationCounter],
                                        APartnerKey,
                                        ref AResponseDS,
                                        ASubmitChangesTransaction,
                                        ref AAddressAddedOrChangedPromotionParametersDT,
                                        ref AChangeLocationParametersDT,
                                        ref APartnerLocationTable,
                                        ref AVerificationResult,
                                        out CreateLocationFlag,
                                        out OriginalLocationKey);

                                if (TmpResult != TSubmitChangesResult.scrOK)
                                {
                                    Result = TmpResult;

                                    if (Result == TSubmitChangesResult.scrError)
                                    {
                                        return Result;
                                    }
                                }

                                if (CreateLocationFlag)
                                {
                                    ModifyExistingLocationParameters(ALocationTable[LocationCounter],
                                        OriginalLocationKey,
                                        ref AExistingLocationParametersDT);

                                    // Make this location's DataRow undmodified because it should not be submitted to the database
                                    ALocationTable.Rows[LocationCounter].AcceptChanges();
                                    LocationCounter--;
                                }
                            } // if CheckHasPartnerLocationOtherPartnerReferences ... then
                        }
                    } // if CheckHasLocationChanged ... then
                    else
                    {
//                      TLogging.LogAtLevel(9, "Location " + ALocationTable[LocationCounter].LocationKey.ToString() + ": data has NOT changed -> will not be saved.");

                        // remove this location because it should not be submitted to the database
                        ALocationTable.Rows.RemoveAt(LocationCounter);
                        LocationCounter--;
                    }
                } // DataRowState.Modified
                else if (ALocationTable.Rows[LocationCounter].RowState == DataRowState.Deleted)
                {
//                  TLogging.LogAtLevel(9, "SubmitChanges: Location " + ALocationTable[LocationCounter]
//                      [PLocationTable.GetLocationKeyDBName(), DataRowVersion.Original].ToString() + ": has been marked for deletion.");

                    // Handle deletion of Location row: delete it only if no other PartnerLocation is referencing it
                    if (CheckHasPartnerLocationOtherPartnerReferences(ALocationTable[LocationCounter], APartnerKey, ASubmitChangesTransaction))
                    {
//                      TLogging.LogAtLevel(9,  TLogging.Log("SubmitChanges: Location " +
//                          ALocationTable[LocationCounter][PLocationTable.GetLocationKeyDBName(), DataRowVersion.Original].ToString() +
//                          ": has been marked for deletion and is used by others, so it won''t get deleted.");

                        // remove this location because it should not be submitted to the database
                        ALocationTable.Rows.RemoveAt(LocationCounter);
                        LocationCounter--;
                    }
                    else
                    {
//                      TLogging.LogAtLevel(9, "SubmitChanges: Location " + ALocationTable[LocationCounter][PLocationTable.GetLocationKeyDBName(),
//                          DataRowVersion.Original].ToString() + ": has been marked for deletion and will get deleted.");

                        // Any Extract in Petra that references this Location must no longer
                        // reference this Location since it will get deleted
                        RemoveLocationFromExtracts(ALocationTable[LocationCounter], ASubmitChangesTransaction);
                    }
                } // if LocationTable.Rows[LocationCounter].RowState = DataRowState.Deleted
                else if (ALocationTable.Rows[LocationCounter].RowState != DataRowState.Unchanged)
                {
                    throw new ArgumentException(
                        "SubmitChanges can only deal with Locations of DataRowState Added, Modified or Deleted, but not with " +
                        (Enum.GetName(typeof(DataRowState), ALocationTable.Rows[LocationCounter].RowState)));
                }
            }

            return Result;
        }
        /// <summary>
        /// Applies Address Security by inspecting all PartnerLocation records'
        /// LocationTypes and the user's presence in security Group ADDRESSCAN.
        /// </summary>
        /// <remarks>
        /// <para>
        /// If the user isn't in the mentioned Security Group, the LocationTypes of all
        /// records are checked.
        /// For any records where the security check fails, the information in all
        /// DataColumns of the Location and PartnerLocation Tables that are present in
        /// the submitted DataTables gets stripped out, Strings get replaced with
        /// StrRestrictedInformation. For the LocationTable this is only true if it is
        /// submitted and holds records that are restricted in the PPartnerLocation
        /// DataTable.
        /// </para>
        /// <para>
        /// <em>Another overload <see cref="M:ApplySecurity(ref DataTable)" /> is available which
        /// can be used if the Partner Location (and/or Location) data isn't available
        /// in the form of the Typed DataTables PPartnerLocation and PLocation!</em>
        /// </para>
        /// </remarks>
        /// <param name="ALocationDT">Location Typed DataTable (optional, set to nil if there is
        /// no Location Typed DataTable that goes with the PartnerLocation Typed
        /// DataTable that is submitted in APartnerLocationDT.</param>
        /// <param name="APartnerLocationDT">PartnerLocation Typed DataTable
        /// </param>
        /// <returns>void</returns>
        public static void ApplySecurity(ref PPartnerLocationTable APartnerLocationDT, ref PLocationTable ALocationDT)
        {
            PPartnerLocationRow PartnerLocationDR;
            PLocationRow LocationDR;

            if (!UserInfo.GUserInfo.IsInGroup(SharedConstants.PETRAGROUP_ADDRESSCAN))
            {
//              TLogging.LogAtLevel(9, "ApplySecurity (2): User isn't in Security Group ADDRESSCAN.");

                foreach (DataRow TmpDR in APartnerLocationDT.Rows)
                {
                    PartnerLocationDR = (PPartnerLocationRow)TmpDR;

                    if (PartnerLocationDR.LocationType.EndsWith(SharedConstants.SECURITY_CAN_LOCATIONTYPE))
                    {
                        /*
                         * Need to strip out information from PPartnerLocation DataTable;
                         * replace Strings with StrRestrictedInformation.
                         */
                        PartnerLocationDR.SetDateEffectiveNull();
                        PartnerLocationDR.SetDateGoodUntilNull();
                        PartnerLocationDR.SendMail = false;
                        PartnerLocationDR.Telex = 0;
                        PartnerLocationDR.LocationDetailComment = Catalog.GetString("** restricted **");
                        PartnerLocationDR.SetDateCreatedNull();
                        PartnerLocationDR.CreatedBy = Catalog.GetString("** restricted **");
                        PartnerLocationDR.SetDateModifiedNull();
                        PartnerLocationDR.ModifiedBy = Catalog.GetString("** restricted **");
                        PartnerLocationDR.AcceptChanges();

                        // Check if we can find this PartnerLocation Row also in the Location DataTable
                        if (ALocationDT != null)
                        {
                            LocationDR = (PLocationRow)ALocationDT.Rows.Find(new System.Object[] { PartnerLocationDR.SiteKey,
                                                                                                   PartnerLocationDR.LocationKey });

                            if (LocationDR != null)
                            {
                                /*
                                 * Location DataTable holds the Row that matches the PartnerLocation Row
                                 * --> Need to strip out information from PLocation DataTable;
                                 * replace Strings with StrRestrictedInformation.
                                 */
                                LocationDR.StreetName = Catalog.GetString("** restricted **");
                                LocationDR.Locality = Catalog.GetString("** restricted **");
                                LocationDR.City = Catalog.GetString("** restricted **");
                                LocationDR.County = Catalog.GetString("** restricted **");
                                LocationDR.PostalCode = Catalog.GetString("** restricted **");

                                // TRANSLATORS: this is used for the restricted country codes
                                LocationDR.CountryCode = Catalog.GetString("99");
                                LocationDR.Address3 = Catalog.GetString("** restricted **");
                                LocationDR.SetDateCreatedNull();
                                LocationDR.CreatedBy = Catalog.GetString("** restricted **");
                                LocationDR.SetDateModifiedNull();
                                LocationDR.ModifiedBy = Catalog.GetString("** restricted **");
                                LocationDR.AcceptChanges();
                            }
                        }
                    }
                }
            }
        }
        /// <summary>
        /// check the location change; validate and take other required action
        /// eg. change the location of family members, promote address changes
        /// </summary>
        /// <param name="ALocationRow"></param>
        /// <param name="APartnerKey"></param>
        /// <param name="AResponseDS"></param>
        /// <param name="ASubmitChangesTransaction"></param>
        /// <param name="AAddressAddedPromotionDT"></param>
        /// <param name="AChangeLocationParametersDT"></param>
        /// <param name="APartnerLocationTable"></param>
        /// <param name="AVerificationResult"></param>
        /// <param name="ACreateLocation"></param>
        /// <param name="AOriginalLocationKey"></param>
        /// <returns></returns>
        private static TSubmitChangesResult PerformLocationChangeChecks(PLocationRow ALocationRow,
            Int64 APartnerKey,
            ref PartnerAddressAggregateTDS AResponseDS,
            TDBTransaction ASubmitChangesTransaction,
            ref PartnerAddressAggregateTDSAddressAddedOrChangedPromotionTable AAddressAddedPromotionDT,
            ref PartnerAddressAggregateTDSChangePromotionParametersTable AChangeLocationParametersDT,
            ref PPartnerLocationTable APartnerLocationTable,
            ref TVerificationResultCollection AVerificationResult,
            out Boolean ACreateLocation,
            out TLocationPK AOriginalLocationKey)
        {
            TSubmitChangesResult ReturnValue;
            DataView PropagateLocationParametersDV;
            DataView PropagateLocationParametersDV2;
            Boolean UpdateLocation;

            Int64[] CreateLocationOtherPartnerKeys;
            PartnerAddressAggregateTDSChangePromotionParametersTable ChangePromotionParametersDT;
            PLocationTable NewLocationTable;
            PLocationRow NewLocationRowSaved;
            Int32 NewLocationLocationKey;
            PPartnerLocationRow PartnerLocationRowForChangedLocation;

            DataSet PartnerLocationModifyDS;
            int Counter;
            Int64 OldLocationKey;
            OdbcParameter[] ParametersArray;
            String OtherPartnerKeys = "";

            AOriginalLocationKey = null;
//          TLogging.LogAtLevel(9, "PerformLocationChangeChecks: AAddressAddedPromotionDT.Rows.Count: " + AAddressAddedPromotionDT.Rows.Count.ToString());

            if (CheckLocationChange(ALocationRow, APartnerKey, ref AAddressAddedPromotionDT, ASubmitChangesTransaction, out UpdateLocation,
                    out ACreateLocation, out CreateLocationOtherPartnerKeys, out ChangePromotionParametersDT))
            {
                // Check if there is a Parameter Row for the LocationKey we are looking at
                PropagateLocationParametersDV = new DataView(AAddressAddedPromotionDT,
                    PartnerAddressAggregateTDSAddressAddedOrChangedPromotionTable.GetSiteKeyDBName() + " = " + ALocationRow.SiteKey.ToString() +
                    " AND " +
                    PartnerAddressAggregateTDSAddressAddedOrChangedPromotionTable.GetLocationKeyDBName() + " = " +
                    ALocationRow.LocationKey.ToString() +
                    " AND " + PartnerAddressAggregateTDSAddressAddedOrChangedPromotionTable.GetLocationChangeDBName() + " = true AND " +
                    PartnerAddressAggregateTDSAddressAddedOrChangedPromotionTable.GetAnswerProcessedClientSideDBName() + " = false",
                    "",
                    DataViewRowState.CurrentRows);

                if (PropagateLocationParametersDV.Count > 0)
                {
//                  TLogging.LogAtLevel(9, "PerformLocationChangeChecks: Location " + ALocationRow.LocationKey.ToString() +
//                          ": Location has been changed, decision on propagation is needed.");

                    /*
                     * More information is needed (usually via user interaction)
                     * -> stop processing here and return parameters
                     * (usually used for UI interaction)
                     */
                    if (AResponseDS == null)
                    {
//                      TLogging.LogAtLevel(9, TLogging.Log("PerformLocationChangeChecks: Creating AResponseDS.");
                        AResponseDS = new PartnerAddressAggregateTDS(MPartnerConstants.PARTNERADDRESSAGGREGATERESPONSE_DATASET);
                    }

//                  TLogging.LogAtLevel(9, "PerformLocationChangeChecks: AAddressAddedPromotionDT.Rows.Count: " + AAddressAddedPromotionDT.Rows.Count.ToString());
                    AResponseDS.Merge(AAddressAddedPromotionDT);
//                  TLogging.LogAtLevel(9, "PerformLocationChangeChecks: Merged AAddressAddedPromotionDT into AResponseDS.");
                    AResponseDS.Merge(ChangePromotionParametersDT);
//                  TLogging.LogAtLevel(9, "PerformLocationChangeChecks: Merged ChangePromotionParametersDT into AResponseDS.");
//                  TLogging.LogAtLevel(9, "PerformLocationChangeChecks: AResponseDS.Tables[" + MPartnerConstants.ADDRESSADDEDORCHANGEDPROMOTION_TABLENAME +
//                      "].Rows.Count: " + AResponseDS.Tables[MPartnerConstants.ADDRESSADDEDORCHANGEDPROMOTION_TABLENAME].Rows.Count.ToString());
                    return TSubmitChangesResult.scrInfoNeeded;
                }
                else
                {
//                  TLogging.LogAtLevel(9, "PerformLocationChangeChecks: User made his/her choice regarding Location Change promotion; now processing...");

                    /*
                     * User made his/her choice regarding Location Change promotion; now process it
                     */
                    if (ACreateLocation)
                    {
                        OldLocationKey = ALocationRow.LocationKey;
                        AOriginalLocationKey = new TLocationPK(
                            Convert.ToInt64(ALocationRow[PLocationTable.GetSiteKeyDBName(),
                                                         DataRowVersion.Original]),
                            Convert.ToInt32(ALocationRow[PLocationTable.GetLocationKeyDBName(),
                                                         DataRowVersion.Original]));

                        // ALocationRow.LocationKey;
//                      TLogging.LogAtLevel(9, "PerformLocationChangeChecks: Location " + AOriginalLocationKey.LocationKey.ToString() + ": should be created.");

                        /*
                         * Create and save NEW Location that holds the same data than the changed
                         * Location.
                         */
                        NewLocationTable = new PLocationTable();
                        NewLocationRowSaved = NewLocationTable.NewRowTyped(false);
                        NewLocationRowSaved.ItemArray = DataUtilities.DestinationSaveItemArray(NewLocationRowSaved, ALocationRow);
                        NewLocationRowSaved.LocationKey = -1;
                        NewLocationTable.Rows.Add(NewLocationRowSaved);

                        // Submit the NEW Location to the DB
                        PLocationAccess.SubmitChanges(NewLocationTable, ASubmitChangesTransaction);

                        // The DB gives us a LocationKey from a Sequence. Remember this one.
                        NewLocationLocationKey = (Int32)NewLocationRowSaved.LocationKey;
//                      TLogging.LogAtLevel(9, "PerformLocationChangeChecks: New Location created! Its Location Key is: " + NewLocationLocationKey.ToString());

                        // Add the new row to the LocationTable that is beeing processed as well
                        // NewLocationCurrentTableRow := (ALocationRow.Table as PLocationTable).NewRowTyped(false);
                        // NewLocationCurrentTableRow.ItemArray := NewLocationRowSaved.ItemArray;
                        // ALocationRow.Table.Rows.Add(NewLocationCurrentTableRow);
                        // Make the row unchanged so that it isn't picked up as a 'new Address'
                        // and that it doesn't get saved later. Will be sent back to the Partner
                        // Edit screen lateron.
                        // NewLocationCurrentTableRow.AcceptChanges;

                        /*
                         * Update the reference from the changed Location to the new Location in
                         * the Partner's PartnerLocation DataTable. This will be saved later in
                         * the call to SubmitChanges in the main loop of the SubmitData function.
                         */
                        PartnerLocationRowForChangedLocation =
                            (PPartnerLocationRow)APartnerLocationTable.Rows.Find(new object[] { APartnerKey, ALocationRow.SiteKey,
                                                                                                ALocationRow.LocationKey });
                        PartnerLocationRowForChangedLocation.LocationKey = NewLocationLocationKey;

                        // Now delete the changed Location so that it doesn't get saved!
                        // ALocationRow.Delete;
                        // ALocationRow.AcceptChanges;
                        // Overwrite the Location that should be replaced with the data of the new Location
                        ALocationRow.ItemArray = NewLocationRowSaved.ItemArray;
                        PropagateLocationParametersDV2 = new DataView(AAddressAddedPromotionDT,
                            PartnerAddressAggregateTDSAddressAddedOrChangedPromotionTable.GetSiteKeyDBName() + " = " +
                            NewLocationRowSaved.SiteKey.ToString() + " AND " +
                            PartnerAddressAggregateTDSAddressAddedOrChangedPromotionTable.GetLocationKeyDBName() + " = " +
                            OldLocationKey.ToString() +
                            " AND " + PartnerAddressAggregateTDSAddressAddedOrChangedPromotionTable.GetLocationChangeDBName() + " = true AND " +
                            PartnerAddressAggregateTDSAddressAddedOrChangedPromotionTable.GetAnswerProcessedClientSideDBName() + " = true",
                            "",
                            DataViewRowState.CurrentRows);
                        ((PartnerAddressAggregateTDSAddressAddedOrChangedPromotionRow)(PropagateLocationParametersDV2[0].Row)).LocationKey =
                            ALocationRow.LocationKey;

                        if (CreateLocationOtherPartnerKeys.Length > 0)
                        {
//                          TLogging.LogAtLevel(9, "PerformLocationChangeChecks: Created Location " + NewLocationLocationKey.ToString() +
//                              ": should be assigned to " + Convert.ToInt32(CreateLocationOtherPartnerKeys.Length).ToString() + " Partners...");

                            // Build list of PartnerKeys for IN (x,y) clause in the SQL statement
                            for (Counter = 0; Counter <= CreateLocationOtherPartnerKeys.Length - 1; Counter += 1)
                            {
                                OtherPartnerKeys = OtherPartnerKeys + CreateLocationOtherPartnerKeys[Counter].ToString() + ',';
                            }

                            // remove last ','
                            OtherPartnerKeys = OtherPartnerKeys.Substring(0, OtherPartnerKeys.Length - 1);

                            // Load data for all the other selected Partners that reference
                            // the PartnerLocation
                            PartnerLocationModifyDS = new DataSet();
                            PartnerLocationModifyDS.Tables.Add(new PPartnerLocationTable());
                            ParametersArray = new OdbcParameter[2];
                            ParametersArray[0] = new OdbcParameter("", OdbcType.Decimal, 10);
                            ParametersArray[0].Value = (System.Object)(NewLocationRowSaved.SiteKey);
                            ParametersArray[1] = new OdbcParameter("", OdbcType.Int);
                            ParametersArray[1].Value = (System.Object)(AOriginalLocationKey.LocationKey);
                            PartnerLocationModifyDS = DBAccess.GDBAccessObj.Select(PartnerLocationModifyDS,
                                "SELECT * " + "FROM PUB_" + PPartnerLocationTable.GetTableDBName() + ' ' + "WHERE " +
                                PPartnerLocationTable.GetPartnerKeyDBName() + " IN (" + OtherPartnerKeys + ") " + "AND " +
                                PPartnerLocationTable.GetSiteKeyDBName() + " = ? " + "AND " + PPartnerLocationTable.GetLocationKeyDBName() + " = ?",
                                PPartnerLocationTable.GetTableName(),
                                ASubmitChangesTransaction,
                                ParametersArray);

                            // Change the LocationKey for every one of those PartnerLocation
                            // DataRows to point to the NEW Location
                            for (Counter = 0; Counter <= CreateLocationOtherPartnerKeys.Length - 1; Counter += 1)
                            {
                                ((PPartnerLocationTable)PartnerLocationModifyDS.Tables[0])[Counter].LocationKey = NewLocationLocationKey;
                            }

                            // Submit the changes to those PartnerLocations to the DB
                            PPartnerLocationAccess.SubmitChanges((PPartnerLocationTable)PartnerLocationModifyDS.Tables[0],
                                ASubmitChangesTransaction);
                        }
                        else
                        {
//                          TLogging.LogAtLevel(9, "PerformLocationChangeChecks: Created Location " + NewLocationLocationKey.ToString() + ": should not be assigned to any other Partners...");

                            /*
                             * Don't need to do anything here - the just created Location got already
                             * assigned to the Partner we are currently working with.
                             */
                        }
                    }
                    else if (UpdateLocation)
                    {
//                      TLogging.LogAtLevel(9, "PerformLocationChangeChecks: Location " + ALocationRow.LocationKey.ToString() +
//                              ": should simply get updated; therefore the Locations of ALL Partners will be changed...");

                        /*
                         * Don't need to do anything here - the changed Location will be saved
                         * in the call to SubmitChanges in the main loop of the SubmitData function.
                         */
                    }
                }

                ReturnValue = TSubmitChangesResult.scrOK;
            }
            else
            {
                TLogging.LogAtLevel(9, "PerformLocationChangeChecks: Location " + ALocationRow.LocationKey.ToString() +
                    ": User cancelled the selection - stopping the whole saving process!");

                /*
                 * User cancelled the selection - stop the whole saving process!
                 */
                AVerificationResult.Add(new TVerificationResult("Location Change Promotion: Information",
                        "No changes were saved because the Location Change Promotion dialog was cancelled by the user.", "Saving cancelled by user",
                        "",
                        TResultSeverity.Resv_Noncritical));
                ReturnValue = TSubmitChangesResult.scrError;
            }

            return ReturnValue;
        }
        /// <summary>
        /// todoComment
        /// </summary>
        /// <param name="ALocationRow"></param>
        /// <param name="APartnerKey"></param>
        /// <param name="AExistingLocationParametersDT"></param>
        /// <param name="AReadTransaction"></param>
        /// <param name="AExistingSiteKey"></param>
        /// <param name="AExistingLocationKey"></param>
        /// <returns></returns>
        private static Boolean CheckReUseExistingLocation(PLocationRow ALocationRow,
            Int64 APartnerKey,
            ref PartnerAddressAggregateTDSSimilarLocationParametersTable AExistingLocationParametersDT,
            TDBTransaction AReadTransaction,
            out Int64 AExistingSiteKey,
            out Int32 AExistingLocationKey)
        {
            Boolean ReturnValue;
            PLocationTable MatchingLocationsDT;
            Boolean FoundSimilarLocation;
            PartnerAddressAggregateTDSSimilarLocationParametersRow SimilarLocationRow;
            PartnerAddressAggregateTDSSimilarLocationParametersRow SimilarLocationParameterRow;
            DataView ExistingLocationParametersDV;
            int LocationUsedByNPartners;
            int Counter;
            PLocationRow MatchingLocationRow;

            AExistingSiteKey = 0;
            AExistingLocationKey = 0;

//              TLogging.LogAtLevel(9,  "CheckReUseExistingLocation for Location " + ALocationRow.LocationKey.ToString() +
//                  ": AExistingLocationParametersDT.Rows.Count: " + AExistingLocationParametersDT.Rows.Count.ToString());

            // Check if there is a Parameter Row for the LocationKey we are looking at
            ExistingLocationParametersDV = new DataView(AExistingLocationParametersDT,
                PartnerAddressAggregateTDSSimilarLocationParametersTable.GetSiteKeyDBName() + " = " + ALocationRow.SiteKey.ToString() + " AND " +
                PartnerAddressAggregateTDSSimilarLocationParametersTable.GetLocationKeyDBName() + " = " + ALocationRow.LocationKey.ToString(),
                "",
                DataViewRowState.CurrentRows);

            // No, there isn't one: perform DB check
            if (ExistingLocationParametersDV.Count == 0)
            {
                FoundSimilarLocation = false;
                #region Look in the DB for *similar* Locations

                // first check how many odbc parameters need to be created
                int CountParameters = 0;
                int CurrentParameter = 0;

                if (!ALocationRow.IsLocalityNull() && (ALocationRow.Locality != ""))
                {
                    CountParameters++;
                }

                if (!ALocationRow.IsStreetNameNull() && (ALocationRow.StreetName != ""))
                {
                    CountParameters++;
                }

                if (!ALocationRow.IsCityNull() && (ALocationRow.City != ""))
                {
                    CountParameters++;
                }

                if (!ALocationRow.IsPostalCodeNull() && (ALocationRow.PostalCode != ""))
                {
                    CountParameters++;
                }

                if (!ALocationRow.IsCountryCodeNull() && (ALocationRow.CountryCode != ""))
                {
                    CountParameters++;
                }

                // initialize parameters and prepare SQL statement
                OdbcParameter[] parameters = new OdbcParameter[CountParameters];
                string sqlLoadSimilarAddresses = "SELECT * FROM PUB_" + PLocationTable.GetTableDBName() + " WHERE";

                // add Locality to query
                sqlLoadSimilarAddresses += " " + PLocationTable.GetLocalityDBName();

                if (ALocationRow.IsLocalityNull() || (ALocationRow.Locality == ""))
                {
                    sqlLoadSimilarAddresses += " is null";
                }
                else
                {
                    sqlLoadSimilarAddresses += " = ?";
                    parameters[CurrentParameter] = new OdbcParameter("Locality", OdbcType.VarChar);
                    parameters[CurrentParameter].Value = ALocationRow.Locality;
                    CurrentParameter++;
                }

                // add Street Name to query
                sqlLoadSimilarAddresses += " AND " + PLocationTable.GetStreetNameDBName();

                if (ALocationRow.IsStreetNameNull() || (ALocationRow.StreetName == ""))
                {
                    sqlLoadSimilarAddresses += " is null";
                }
                else
                {
                    sqlLoadSimilarAddresses += " = ?";
                    parameters[CurrentParameter] = new OdbcParameter("StreetName", OdbcType.VarChar);
                    parameters[CurrentParameter].Value = ALocationRow.StreetName;
                    CurrentParameter++;
                }

                // add City to query
                sqlLoadSimilarAddresses += " AND " + PLocationTable.GetCityDBName();

                if (ALocationRow.IsCityNull() || (ALocationRow.City == ""))
                {
                    sqlLoadSimilarAddresses += " is null";
                }
                else
                {
                    sqlLoadSimilarAddresses += " = ?";
                    parameters[CurrentParameter] = new OdbcParameter("City", OdbcType.VarChar);
                    parameters[CurrentParameter].Value = ALocationRow.City;
                    CurrentParameter++;
                }

                // add Post Code to query
                sqlLoadSimilarAddresses += " AND " + PLocationTable.GetPostalCodeDBName();

                if (ALocationRow.IsPostalCodeNull() || (ALocationRow.PostalCode == ""))
                {
                    sqlLoadSimilarAddresses += " is null";
                }
                else
                {
                    sqlLoadSimilarAddresses += " = ?";
                    parameters[CurrentParameter] = new OdbcParameter("PostalCode", OdbcType.VarChar);
                    parameters[CurrentParameter].Value = ALocationRow.PostalCode;
                    CurrentParameter++;
                }

                // add Country Code to query
                sqlLoadSimilarAddresses += " AND " + PLocationTable.GetCountryCodeDBName();

                if (ALocationRow.IsCountryCodeNull() || (ALocationRow.CountryCode == ""))
                {
                    sqlLoadSimilarAddresses += " is null";
                }
                else
                {
                    sqlLoadSimilarAddresses += " = ?";
                    parameters[CurrentParameter] = new OdbcParameter("CountryCode", OdbcType.VarChar);
                    parameters[CurrentParameter].Value = ALocationRow.CountryCode;
                    CurrentParameter++;
                }

                MatchingLocationsDT = new PLocationTable();

                // run query to find similar locations
                DBAccess.GDBAccessObj.SelectDT(MatchingLocationsDT, sqlLoadSimilarAddresses, AReadTransaction, parameters, 0, 0);

                /*
                 * Note: County and Address3 are not searched for - we are looking for a
                 * Location that is *similar*!
                 */
                MatchingLocationRow = null;  // to avoid compiler warning

                if (MatchingLocationsDT.Rows.Count != 0)
                {
                    // check if any of the returned Rows is not the current Row
                    for (Counter = 0; Counter <= MatchingLocationsDT.Rows.Count - 1; Counter += 1)
                    {
                        if (MatchingLocationsDT[Counter].LocationKey != ALocationRow.LocationKey)
                        {
                            FoundSimilarLocation = true;
                            AExistingSiteKey = MatchingLocationsDT[Counter].SiteKey;
                            AExistingLocationKey = (int)MatchingLocationsDT[Counter].LocationKey;
                            MatchingLocationRow = (PLocationRow)MatchingLocationsDT[Counter];
                            break;
                        }
                    }
                }
                else
                {
                    FoundSimilarLocation = false;
                }

                #endregion

                if (FoundSimilarLocation)
                {
//                  TLogging.LogAtLevel(9,  "CheckReUseExistingLocation: Location " + ALocationRow.LocationKey.ToString() + ": found a similar Location (" + AExistingLocationKey.ToString() + ")!");
                    AExistingLocationParametersDT = new PartnerAddressAggregateTDSSimilarLocationParametersTable(
                        MPartnerConstants.EXISTINGLOCATIONPARAMETERS_TABLENAME);
                    LocationUsedByNPartners =
                        (Int16)(PPartnerLocationAccess.CountViaPLocation(AExistingSiteKey, AExistingLocationKey, AReadTransaction));
//                  TLogging.LogAtLevel(9, "CheckReUseExistingLocation: LocationUsedByNPartners: " + LocationUsedByNPartners.ToString());
                    SimilarLocationRow = AExistingLocationParametersDT.NewRowTyped(false);
                    SimilarLocationRow.SiteKey = ALocationRow.SiteKey;
                    SimilarLocationRow.LocationKey = ALocationRow.LocationKey;
                    SimilarLocationRow.Locality = TSaveConvert.StringColumnToString(MatchingLocationsDT.ColumnLocality, MatchingLocationRow);
                    SimilarLocationRow.StreetName = TSaveConvert.StringColumnToString(MatchingLocationsDT.ColumnStreetName, MatchingLocationRow);
                    SimilarLocationRow.Address3 = TSaveConvert.StringColumnToString(MatchingLocationsDT.ColumnAddress3, MatchingLocationRow);
                    SimilarLocationRow.City = TSaveConvert.StringColumnToString(MatchingLocationsDT.ColumnCity, MatchingLocationRow);
                    SimilarLocationRow.PostalCode = TSaveConvert.StringColumnToString(MatchingLocationsDT.ColumnPostalCode, MatchingLocationRow);
                    SimilarLocationRow.County = TSaveConvert.StringColumnToString(MatchingLocationsDT.ColumnCounty, MatchingLocationRow);
                    SimilarLocationRow.CountryCode = TSaveConvert.StringColumnToString(MatchingLocationsDT.ColumnCountryCode, MatchingLocationRow);

                    if (LocationUsedByNPartners > 0)
                    {
                        SimilarLocationRow.UsedByNOtherPartners = LocationUsedByNPartners;
                    }
                    else
                    {
                        SimilarLocationRow.UsedByNOtherPartners = 0;
                    }

                    SimilarLocationRow.SiteKeyOfSimilarLocation = AExistingSiteKey;
                    SimilarLocationRow.LocationKeyOfSimilarLocation = AExistingLocationKey;
                    SimilarLocationRow.AnswerProcessedClientSide = false;
                    SimilarLocationRow.AnswerProcessedServerSide = false;
                    AExistingLocationParametersDT.Rows.Add(SimilarLocationRow);
                    SimilarLocationRow.AcceptChanges();
                    ReturnValue = true;
                }
                else
                {
//                  TLogging.LogAtLevel(9,  "CheckReUseExistingLocation: Location " + ALocationRow.LocationKey.ToString() + ": found no similar Location.");
                    ReturnValue = false;
                }
            }
            else
            {
                // AExistingLocationParametersDT was passed in, holding parameters for the LocationKey we are looking at
                SimilarLocationParameterRow = (PartnerAddressAggregateTDSSimilarLocationParametersRow)ExistingLocationParametersDV[0].Row;

                if (SimilarLocationParameterRow.AnswerReuse)
                {
                    AExistingSiteKey = SimilarLocationParameterRow.SiteKeyOfSimilarLocation;
                    AExistingLocationKey = SimilarLocationParameterRow.LocationKeyOfSimilarLocation;
//                  TLogging.LogAtLevel(9, "CheckReUseExistingLocation: AExistingLocationParametersDT tells me to re-use existing Location " +
//                      AExistingLocationParametersDT[0].LocationKeyOfSimilarLocation.ToString() + '.');
                    SimilarLocationParameterRow.AnswerProcessedClientSide = true;

                    // SimilarLocationParameterRow.AcceptChanges;
                    ReturnValue = true;
                }
                else
                {
//                  TLogging.LogAtLevel(9, "CheckReUseExistingLocation: AExistingLocationParametersDT tells me NOT to re-use existing Location.");
                    SimilarLocationParameterRow.AnswerProcessedClientSide = true;

                    // SimilarLocationParameterRow.AcceptChanges;
                    ReturnValue = false;
                }
            }

            return ReturnValue;
        }
Exemple #31
0
        /// <summary>
        /// This report considers gifts given between the two specified dates, and can include all gifts or, if
        /// selected, those to a particular motivation, motivation detail or recipient. For the defined set of gifts
        /// and its total value, the donors are sorted into a list, starting with those who gave most, and showing
        /// the percentage that their gifts contributed to the total received (for this motivation or recipient, if
        /// specified) and the cumulative percentage, moving down the list starting with the top donor.
        /// </summary>
        /// <param name="ATotalAmount">Pre calculated value of the total gifts given with these parameters</param>
        /// <param name="ATopXPercent">Upper limit of the percentage to show in the report</param>
        /// <param name="ABottomXPercent">Lower limit of the percentage to show in the report</param>
        /// <param name="AExtract">true to use only partners from an extract</param>
        /// <param name="AExtractName">extract name</param>
        /// <param name="AStartDate">Start date of the gifts given</param>
        /// <param name="AEndDate">End date of the gifts given</param>
        /// <param name="ARecipientKey">Partner key of a specific recipient. If 0 then use all recipients</param>
        /// <param name="AMotivationGroup">Limit gifts to this motivation group. If % use all motivation groups</param>
        /// <param name="AMotivationDetail">Limit gifts to this motivation detail. If % use all motivation details</param>
        /// <returns></returns>
        private bool MakeTopDonor(decimal ATotalAmount, decimal ATopXPercent, decimal ABottomXPercent,
                                  bool AExtract, String AExtractName, DateTime AStartDate, DateTime AEndDate,
                                  Int64 ARecipientKey, String AMotivationGroup, String AMotivationDetail)
        {
            Int64         LedgerNumber = situation.GetParameters().Get("param_ledger_number_i").ToInt64();
            String        CurrencyType = situation.GetParameters().Get("param_currency").ToString();
            StringBuilder SqlString    = new StringBuilder();

            SqlString.Append("SELECT DISTINCT ");
            SqlString.Append("gift.p_donor_key_n AS DonorKey, ");
            SqlString.Append(PPartnerTable.GetTableDBName() + "." + PPartnerTable.GetPartnerShortNameDBName() + " AS ShortName, ");
            SqlString.Append(PPartnerTable.GetTableDBName() + "." + PPartnerTable.GetPartnerClassDBName() + " AS PartnerClass, ");

            if (CurrencyType == "Base")
            {
                SqlString.Append("SUM(detail." + AGiftDetailTable.GetGiftAmountDBName() + ") AS Amount ");
            }
            else
            {
                SqlString.Append("SUM(detail." + AGiftDetailTable.GetGiftAmountIntlDBName() + ") AS Amount ");
            }

            SqlString.Append(
                " FROM " + AGiftTable.GetTableDBName() + " as gift, " + AGiftDetailTable.GetTableDBName() + " as detail, " +
                PPartnerTable.GetTableDBName() + ", " + AGiftBatchTable.GetTableDBName() + " ");

            if (AExtract)
            {
                SqlString.Append(", " + MExtractTable.GetTableDBName() + ", " + MExtractMasterTable.GetTableDBName());
                SqlString.Append(
                    " WHERE gift." + AGiftTable.GetDonorKeyDBName() + " = " + MExtractTable.GetTableDBName() + "." +
                    MExtractTable.GetPartnerKeyDBName());
                SqlString.Append(
                    " AND " + MExtractTable.GetTableDBName() + "." + MExtractTable.GetExtractIdDBName() + " = " +
                    MExtractMasterTable.GetTableDBName() +
                    "." + MExtractMasterTable.GetExtractIdDBName());
                SqlString.Append(" AND " + MExtractMasterTable.GetTableDBName() + "." + MExtractMasterTable.GetExtractNameDBName() + " = '");
                SqlString.Append(AExtractName);
                SqlString.Append("' AND ");
            }
            else
            {
                SqlString.Append(" WHERE ");
            }

            SqlString.Append(" detail." + AGiftDetailTable.GetLedgerNumberDBName() + " = gift." + AGiftTable.GetLedgerNumberDBName());
            SqlString.Append(" AND detail." + AGiftDetailTable.GetBatchNumberDBName() + " = gift." + AGiftTable.GetBatchNumberDBName());
            SqlString.Append(
                " AND detail." + AGiftDetailTable.GetGiftTransactionNumberDBName() + " = gift." + AGiftTable.GetGiftTransactionNumberDBName());
            SqlString.Append(" AND gift." + AGiftTable.GetDateEnteredDBName() + " BETWEEN '");
            SqlString.Append(AStartDate.ToString("yyyy-MM-dd"));
            SqlString.Append("' AND '");
            SqlString.Append(AEndDate.ToString("yyyy-MM-dd"));
            SqlString.Append("' AND gift." + AGiftTable.GetLedgerNumberDBName() + " = ");
            SqlString.Append(LedgerNumber.ToString());
            SqlString.Append(" AND " + AGiftBatchTable.GetTableDBName() + "." + AGiftBatchTable.GetLedgerNumberDBName() + " = ");
            SqlString.Append(LedgerNumber.ToString());
            SqlString.Append(
                " AND " + AGiftBatchTable.GetTableDBName() + "." + AGiftBatchTable.GetBatchNumberDBName() + " = gift." +
                AGiftTable.GetBatchNumberDBName());
            SqlString.Append(" AND ( " + AGiftBatchTable.GetTableDBName() + "." + AGiftBatchTable.GetBatchStatusDBName() + " = 'Posted' OR ");
            SqlString.Append(AGiftBatchTable.GetTableDBName() + "." + AGiftBatchTable.GetBatchStatusDBName() + " = 'posted' ) ");
            SqlString.Append(
                " AND " + PPartnerTable.GetTableDBName() + "." + PPartnerTable.GetPartnerKeyDBName() + " = gift." + AGiftTable.GetDonorKeyDBName());

            if (ARecipientKey != 0)
            {
                SqlString.Append(" AND detail." + AGiftDetailTable.GetRecipientKeyDBName() + " = ");
                SqlString.Append(ARecipientKey.ToString());
            }

            if (AMotivationGroup != "%")
            {
                SqlString.Append(" AND  detail." + AGiftDetailTable.GetMotivationGroupCodeDBName() + " LIKE '");
                SqlString.Append(AMotivationGroup);
                SqlString.Append("' ");
            }

            if (AMotivationDetail != "%")
            {
                SqlString.Append(" AND  detail." + AGiftDetailTable.GetMotivationDetailCodeDBName() + " LIKE '");
                SqlString.Append(AMotivationDetail);
                SqlString.Append("' ");
            }

            SqlString.Append(" GROUP BY gift." + AGiftTable.GetDonorKeyDBName() + ", ");
            SqlString.Append(PPartnerTable.GetTableDBName() + "." + PPartnerTable.GetPartnerShortNameDBName() + ", ");
            SqlString.Append(PPartnerTable.GetTableDBName() + "." + PPartnerTable.GetPartnerClassDBName());
            SqlString.Append(" ORDER BY Amount DESC");

            DataTable Table = situation.GetDatabaseConnection().SelectDT(SqlString.ToString(), "table",
                                                                         situation.GetDatabaseConnection().Transaction, new OdbcParameter[] { });

            decimal CummulativeAmount = 0;
            decimal TopAmount         = ATotalAmount * ATopXPercent / 100;
            decimal BottomAmount      = ATotalAmount * ABottomXPercent / 100;

            int NumColumns = 7;
            int ChildRow   = 1;

            situation.GetResults().Clear();

            for (int Counter = 0; Counter < Table.Rows.Count; ++Counter)
            {
                decimal CurrentAmount = Convert.ToDecimal(Table.Rows[Counter]["Amount"]);

                if (CurrentAmount < 0)
                {
                    continue;
                }

                if ((CummulativeAmount <= TopAmount) &&
                    (CummulativeAmount >= BottomAmount))
                {
                    Int64  DonorKey     = Convert.ToInt64(Table.Rows[Counter]["DonorKey"]);
                    String ShortName    = (String)Table.Rows[Counter]["ShortName"];
                    String PartnerClass = (String)Table.Rows[Counter]["PartnerClass"];

                    CummulativeAmount += CurrentAmount;

                    // Transfer to results
                    TVariant[] Header      = new TVariant[NumColumns];
                    TVariant[] Description =
                    {
                        new TVariant(), new TVariant()
                    };
                    TVariant[] Columns = new TVariant[NumColumns];

                    for (int Counter2 = 0; Counter2 < NumColumns; ++Counter2)
                    {
                        Header[Counter2]  = new TVariant();
                        Columns[Counter2] = new TVariant();
                    }

                    StringBuilder       PartnerAddress = new StringBuilder();
                    PPartnerLocationRow AddressRow;

                    if (Ict.Petra.Server.MReporting.MPartner.TRptUserFunctionsPartner.GetPartnerBestAddressRow(DonorKey, situation, out AddressRow))
                    {
                        PLocationTable LocationTable = PLocationAccess.LoadByPrimaryKey(AddressRow.SiteKey,
                                                                                        AddressRow.LocationKey, situation.GetDatabaseConnection().Transaction);

                        if (LocationTable.Rows.Count > 0)
                        {
                            PLocationRow LocationRow = (PLocationRow)LocationTable.Rows[0];

                            PartnerAddress.Append(LocationRow.Locality);

                            if (LocationRow.Locality.Length > 0)
                            {
                                PartnerAddress.Append(", ");
                            }

                            PartnerAddress.Append(LocationRow.StreetName);

                            if (PartnerAddress.Length > 0)
                            {
                                PartnerAddress.Append(", ");
                            }

                            PartnerAddress.Append(LocationRow.Address3);

                            if (PartnerAddress.Length > 0)
                            {
                                PartnerAddress.Append(", ");
                            }

                            PartnerAddress.Append(LocationRow.PostalCode);
                            PartnerAddress.Append(" ");
                            PartnerAddress.Append(LocationRow.City);

                            if (LocationRow.County.Length > 0)
                            {
                                PartnerAddress.Append(", ");
                                PartnerAddress.Append(LocationRow.County);
                            }

                            PartnerAddress.Append(", ");
                            PartnerAddress.Append(LocationRow.CountryCode);
                        }
                    }

                    Columns[0] = new TVariant(DonorKey.ToString("0000000000"));
                    Columns[1] = new TVariant(PartnerClass);
                    Columns[2] = new TVariant(ShortName);
                    Columns[3] = new TVariant(CurrentAmount, "-#,##0.00;#,##0.00");
                    Columns[4] = new TVariant((CurrentAmount * 100 / ATotalAmount), "-#,##0.00;#,##0.00");
                    Columns[5] = new TVariant((CummulativeAmount * 100 / ATotalAmount), "-#,##0.00;#,##0.00");
                    Columns[6] = new TVariant(PartnerAddress.ToString());

                    situation.GetResults().AddRow(0, ChildRow++, true, 2, "", "", false,
                                                  Header, Description, Columns);
                }
                else
                {
                    CummulativeAmount += CurrentAmount;
                }
            }

            return(true);
        }
        public static void FindAddressDuplicates(ref DataTable ADuplicateAddresses, bool AExactMatchNumber)
        {
            TDBTransaction Transaction = null;
            DataTable ReturnTable = ADuplicateAddresses.Clone();
            PLocationTable Locations = new PLocationTable();

            TProgressTracker.InitProgressTracker(DomainManager.GClientID.ToString(), Catalog.GetString("Checking for duplicate addresses"));

            DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted, ref Transaction,
                delegate
                {
                    // get all locations from database,
                    // except for those without a Locality, Street Name and Address as these are too vague to make a match
                    string Query = "SELECT p_location.* FROM p_location" +
                                   " WHERE (p_location.p_locality_c is NOT NULL AND p_location.p_locality_c <> '')" +
                                   " OR (p_location.p_street_name_c is NOT NULL AND p_location.p_street_name_c <> '')" +
                                   " OR (p_location.p_address_3_c is NOT NULL AND p_location.p_address_3_c <> '')";

                    DBAccess.GDBAccessObj.SelectDT(Locations, Query, Transaction);

                    // create a list of tables grouped by country codes
                    List <DataTable>LocationDataTables = Locations.AsEnumerable()
                                                         .GroupBy(row => row[PLocationTable.GetCountryCodeDBName()])
                                                         .Select(g => g.CopyToDataTable())
                                                         .ToList();

                    DataTable BlankCountryLocations = Locations.Clone();

                    // create another table that contains all locations without a valid country code
                    for (int i = 0; i < LocationDataTables.Count; i++)
                    {
                        // this helps the time left feature to be more accurate from the start
                        LocationDataTables[i].DefaultView.Sort = PLocationTable.GetPostalCodeDBName() + " DESC";
                        LocationDataTables[i] = LocationDataTables[i].DefaultView.ToTable();

                        if (string.IsNullOrEmpty(LocationDataTables[i].Rows[0]["p_country_code_c"].ToString())
                            || (LocationDataTables[i].Rows[0]["p_country_code_c"].ToString() == "99"))
                        {
                            foreach (DataRow Row in LocationDataTables[i].Rows)
                            {
                                BlankCountryLocations.Rows.Add((object[])Row.ItemArray.Clone());
                            }
                        }
                    }

                    Int64 TotalCalculations = 0;
                    Int64 CompletedCalculations = 0;
                    decimal PercentageCompleted = 0;

                    // calculate number of calculations required for this check
                    for (int i = 0; i < LocationDataTables.Count; i++)
                    {
                        if (LocationDataTables[i].Rows.Count > 0)
                        {
                            TotalCalculations += ((Int64)LocationDataTables[i].Rows.Count) * ((Int64)LocationDataTables[i].Rows.Count - 1) / 2;

                            // if not table containing invalid country codes
                            if (!string.IsNullOrEmpty(LocationDataTables[i].Rows[0]["p_country_code_c"].ToString())
                                && (LocationDataTables[i].Rows[0]["p_country_code_c"].ToString() != "99"))
                            {
                                TotalCalculations += BlankCountryLocations.Rows.Count;
                            }
                        }
                    }

                    Int64 TimeLeft;
                    int MinutesLeft;
                    int SecondsLeft;
                    Stopwatch time = Stopwatch.StartNew();

                    // begin search for possible duplicates
                    foreach (DataTable LocationCountry in LocationDataTables)
                    {
                        if (LocationCountry.Rows.Count <= 0)
                        {
                            continue;
                        }

                        for (int i = 0; i < LocationCountry.Rows.Count; i++)
                        {
                            string AAddress = null;
                            string[] AAddressArray = null;

                            for (int j = i + 1; j < LocationCountry.Rows.Count; j++)
                            {
                                // check if two rows are a possible duplicate
                                if (PossibleMatch(LocationCountry.Rows[i], ref AAddress, ref AAddressArray, LocationCountry.Rows[j],
                                        AExactMatchNumber))
                                {
                                    ReturnTable.Rows.Add(new object[] {
                                            LocationCountry.Rows[i][PLocationTable.GetSiteKeyDBName()],
                                            LocationCountry.Rows[i][PLocationTable.GetLocationKeyDBName()],
                                            LocationCountry.Rows[i][PLocationTable.GetLocalityDBName()],
                                            LocationCountry.Rows[i][PLocationTable.GetStreetNameDBName()],
                                            LocationCountry.Rows[i][PLocationTable.GetAddress3DBName()],
                                            LocationCountry.Rows[i][PLocationTable.GetCityDBName()],
                                            LocationCountry.Rows[i][PLocationTable.GetCountyDBName()],
                                            LocationCountry.Rows[i][PLocationTable.GetPostalCodeDBName()],
                                            LocationCountry.Rows[i][PLocationTable.GetCountryCodeDBName()],
                                            LocationCountry.Rows[j][PLocationTable.GetSiteKeyDBName()],
                                            LocationCountry.Rows[j][PLocationTable.GetLocationKeyDBName()],
                                            LocationCountry.Rows[j][PLocationTable.GetLocalityDBName()],
                                            LocationCountry.Rows[j][PLocationTable.GetStreetNameDBName()],
                                            LocationCountry.Rows[j][PLocationTable.GetAddress3DBName()],
                                            LocationCountry.Rows[j][PLocationTable.GetCityDBName()],
                                            LocationCountry.Rows[j][PLocationTable.GetCountyDBName()],
                                            LocationCountry.Rows[j][PLocationTable.GetPostalCodeDBName()],
                                            LocationCountry.Rows[j][PLocationTable.GetCountryCodeDBName()]
                                        });
                                }

                                CompletedCalculations++;
                            }

                            // if not table containing invalid country codes
                            if (!string.IsNullOrEmpty(LocationCountry.Rows[0]["p_country_code_c"].ToString())
                                && (LocationCountry.Rows[0]["p_country_code_c"].ToString() != "99"))
                            {
                                // compare with locations with invalid country codes
                                for (int j = 0; j < BlankCountryLocations.Rows.Count; j++)
                                {
                                    if (PossibleMatch(LocationCountry.Rows[i], ref AAddress, ref AAddressArray, BlankCountryLocations.Rows[j],
                                            AExactMatchNumber))
                                    {
                                        ReturnTable.Rows.Add(new object[] {
                                                LocationCountry.Rows[i][PLocationTable.GetSiteKeyDBName()],
                                                LocationCountry.Rows[i][PLocationTable.GetLocationKeyDBName()],
                                                LocationCountry.Rows[i][PLocationTable.GetLocalityDBName()],
                                                LocationCountry.Rows[i][PLocationTable.GetStreetNameDBName()],
                                                LocationCountry.Rows[i][PLocationTable.GetAddress3DBName()],
                                                LocationCountry.Rows[i][PLocationTable.GetCityDBName()],
                                                LocationCountry.Rows[i][PLocationTable.GetCountyDBName()],
                                                LocationCountry.Rows[i][PLocationTable.GetPostalCodeDBName()],
                                                LocationCountry.Rows[i][PLocationTable.GetCountryCodeDBName()],
                                                BlankCountryLocations.Rows[j][PLocationTable.GetSiteKeyDBName()],
                                                BlankCountryLocations.Rows[j][PLocationTable.GetLocationKeyDBName()],
                                                BlankCountryLocations.Rows[j][PLocationTable.GetLocalityDBName()],
                                                BlankCountryLocations.Rows[j][PLocationTable.GetStreetNameDBName()],
                                                BlankCountryLocations.Rows[j][PLocationTable.GetAddress3DBName()],
                                                BlankCountryLocations.Rows[j][PLocationTable.GetCityDBName()],
                                                BlankCountryLocations.Rows[j][PLocationTable.GetCountyDBName()],
                                                BlankCountryLocations.Rows[j][PLocationTable.GetPostalCodeDBName()],
                                                BlankCountryLocations.Rows[j][PLocationTable.GetCountryCodeDBName()]
                                            });
                                    }

                                    CompletedCalculations++;
                                }
                            }

                            if (TProgressTracker.GetCurrentState(DomainManager.GClientID.ToString()).CancelJob)
                            {
                                break;
                            }

                            // estimate the remaining time
                            PercentageCompleted = decimal.Divide(CompletedCalculations * 100, TotalCalculations);
                            TimeLeft = (Int64)(time.ElapsedMilliseconds * ((100 / PercentageCompleted) - 1));
                            MinutesLeft = (int)TimeLeft / 60000;

                            string OutputMessage = string.Format(Catalog.GetString("Completed: {0}%"), Math.Round(PercentageCompleted, 1));

                            // only show estimated time left if at least 0.1% complete
                            if (PercentageCompleted >= (decimal)0.1)
                            {
                                // only show seconds if less than 10 minutes remaining
                                if (MinutesLeft < 10)
                                {
                                    SecondsLeft = (int)(TimeLeft % 60000) / 1000;

                                    OutputMessage += string.Format(Catalog.GetPluralString(" (approx. {0} minute and {1} seconds remaining)",
                                            " (approx. {0} minutes and {1} seconds remaining)", MinutesLeft, true),
                                        MinutesLeft, SecondsLeft);
                                }
                                else
                                {
                                    OutputMessage += string.Format(Catalog.GetString(" (approx. {0} minutes remaining)"),
                                        MinutesLeft);
                                }
                            }

                            TProgressTracker.SetCurrentState(DomainManager.GClientID.ToString(),
                                OutputMessage,
                                PercentageCompleted);
                        }
                    }
                });

            TProgressTracker.FinishJob(DomainManager.GClientID.ToString());

            ADuplicateAddresses = ReturnTable.Copy();
        }
        /// <summary>
        /// Creates a new DataRow in the passed PLocation and PPartnerLocation tables.
        /// </summary>
        /// <param name="ALocationDT">Typed PLocation table. If null is passed in it is created
        /// automatically</param>
        /// <param name="APartnerLocationDT">Typed PPartnerLocation table. If null is passed in
        /// it is created automatically</param>
        /// <param name="APartnerKey">PartneKey of the Partner for which the Address should
        /// be created</param>
        /// <param name="APartnerClass">PartnerClass of the Partner for which the Address should
        /// be created</param>
        /// <param name="ACountryCode"></param>
        /// <param name="ANewLocationKey">A LocationKey that the new Location and
        /// PartnerLocation rows would be set to.</param>
        /// <param name="ACopyFromFamilyPartnerKey">Pass in the PartnerKey of a Family Partner
        /// to copy over all data from the Family's Address
        /// (ACopyFromPartnerLocationKey must be -1 to be legal). Default: -1
        /// (=no copy). Note: the DataRow specified with ACopyFromFamilyPartnerKey must
        /// be present in the APartnerLocationDT table!</param>
        /// <param name="ACopyFromFamilyLocationKey">Pass in the LocationKey of the Family
        /// Partner specified in ACopyFromFamilyPartnerKey to copy over all data from
        /// the Family's Address (ACopyFromPartnerLocationKey must be -1 to be legal)
        /// Default: -1 (=no copy). Note: the DataRow specified with
        /// ACopyFromFamilyLocationKey must be present in both the ALocationDT and
        /// APartnerLocationDT table!</param>
        /// <param name="ACopyFromFamilySiteKey">A SiteKey to find the location that should be the
        /// source of the copy</param>
        /// <param name="ACopyFromFamilyOnlyLocation"></param>
        /// <param name="ADeleteDataRowCopiedFrom"></param>
        /// <exception cref="ArgumentException">If any of the Arguments (or their combination) is
        /// not valid.</exception>
        public static void CreateNewAddressInternal(PLocationTable ALocationDT,
            PPartnerLocationTable APartnerLocationDT,
            Int64 APartnerKey,
            TPartnerClass APartnerClass,
            String ACountryCode,
            Int32 ANewLocationKey,
            Int64 ACopyFromFamilyPartnerKey,
            Int32 ACopyFromFamilyLocationKey,
            Int64 ACopyFromFamilySiteKey,
            Boolean ACopyFromFamilyOnlyLocation,
            Boolean ADeleteDataRowCopiedFrom)
        {
            PLocationRow NewLocationsRow;
            PLocationRow CopyLocationsRow;
            PPartnerLocationRow NewPartnerLocationRow;
            PPartnerLocationRow CopyPartnerLocationRow;

            #region Check parameters

            if (ALocationDT == null)
            {
                ALocationDT = new PLocationTable();
            }

            if (APartnerLocationDT == null)
            {
                APartnerLocationDT = new PPartnerLocationTable();
            }

            if (TStaticDataTables.TMPartner.GetStaticTable(TStaticPartnerTablesEnum.PartnerClassList).Rows.Find(APartnerClass) == null)
            {
                throw new ArgumentException("APartnerClass needs to be a valid Partner Class");
            }

            if ((ACopyFromFamilyPartnerKey != -1) || (ACopyFromFamilyLocationKey != -99))
            {
                if (ACopyFromFamilyPartnerKey != -1)
                {
                    if (ACopyFromFamilyLocationKey == -99)
                    {
                        throw new ArgumentException("ACopyFromFamilyLocationKey needs to be specified if ACopyFromFamilyPartnerKey is specified");
                    }
                }

                if (ACopyFromFamilyLocationKey != -99)
                {
                    if (ACopyFromFamilyPartnerKey == -1)
                    {
                        throw new ArgumentException("ACopyFromFamilyPartnerKey needs to be specified if ACopyFromFamilyLocationKey is specified");
                    }
                }
            }

            #endregion

            /*
             * Add new Locations row
             */
            NewLocationsRow = ALocationDT.NewRowTyped(true);

            // Assign Primary Key columns
            NewLocationsRow.SiteKey = SharedConstants.FIXED_SITE_KEY; // TODO: use s_system_parameter.s_site_key_n once p_partner_location actually uses the Petra System SiteKey in the PrimaryKey (instead of 0, which is used currently)
            NewLocationsRow.LocationKey = ANewLocationKey;

            // Copy over Columns of the Row specified with ACopyFromFamilyLocationKey?
            if (ACopyFromFamilyLocationKey != -99)
            {
                CopyLocationsRow = (PLocationRow)ALocationDT.Rows.Find(new Object[] { ACopyFromFamilySiteKey, ACopyFromFamilyLocationKey });

                if (CopyLocationsRow != null)
                {
                    if (ACountryCode != "")
                    {
                        throw new ArgumentException(
                            "ACountryCode must not be specified because it would be overwritten by the value from the row specified with ACopyFromFamilyLocationKey");
                    }

                    CopyLocationData(CopyLocationsRow, NewLocationsRow);

                    if (ADeleteDataRowCopiedFrom)
                    {
                        CopyLocationsRow.Delete();
                        CopyLocationsRow.AcceptChanges();
                    }
                }
                else
                {
                    throw new ArgumentException("Row with specified ACopyFromFamilyLocationKey cannot be found in PLocations DataTable!");
                }
            }
            else
            {
                // No copying > assign values of columns manually
                NewLocationsRow.CountryCode = ACountryCode;
            }

            NewLocationsRow.CreatedBy = UserInfo.GUserInfo.UserID;
            ALocationDT.Rows.Add(NewLocationsRow);

            // If an existing Location shouldn't be copied to a temp LocationKey (<0) then make this DataRow unchanged
            // (prevents this row from getting commited to the PetraServer).
            if (ANewLocationKey >= 0)
            {
                NewLocationsRow.AcceptChanges();
            }

            /*
             * Add new PartnerLocations row
             */
            NewPartnerLocationRow = APartnerLocationDT.NewRowTyped(true);

            // Assign Primary Key columns
            NewPartnerLocationRow.PartnerKey = APartnerKey;
            NewPartnerLocationRow.SiteKey = SharedConstants.FIXED_SITE_KEY; // TODO: use s_system_parameter.s_site_key_n once p_partner_location actually uses the Petra System SiteKey in the PrimaryKey (instead of 0, which is used currently)
            NewPartnerLocationRow.LocationKey = ANewLocationKey;

            // Copy over Columns of the Row specified with ACopyFromFamilyPartnerKey
            // and ACopyFromFamilyLocationKey?
            if ((!ACopyFromFamilyOnlyLocation) && (ACopyFromFamilyLocationKey != -99))
            {
                CopyPartnerLocationRow =
                    (PPartnerLocationRow)APartnerLocationDT.Rows.Find(new Object[] { ACopyFromFamilyPartnerKey, ACopyFromFamilySiteKey,
                                                                                     ACopyFromFamilyLocationKey });

                if (CopyPartnerLocationRow != null)
                {
                    // Security check for LocationType SECURITY_CAN_LOCATIONTYPE
                    if (((CopyPartnerLocationRow.LocationType.EndsWith(SharedConstants.SECURITY_CAN_LOCATIONTYPE)
                          && (UserInfo.GUserInfo.IsInGroup(SharedConstants.PETRAGROUP_ADDRESSCAN))))
                        || (!((CopyPartnerLocationRow.LocationType.EndsWith(SharedConstants.SECURITY_CAN_LOCATIONTYPE)))))
                    {
                        // Copy over all columns, except the Primary Key columns and the last four
                        // columns (containing creation and change information)
                        NewPartnerLocationRow.LocationType = CopyPartnerLocationRow.LocationType;

                        if (!CopyPartnerLocationRow.IsDateGoodUntilNull())
                        {
                            // Copy over DateGoodUntil only if it doesn't lie in the past
                            if (CopyPartnerLocationRow.DateGoodUntil >= DateTime.Today)
                            {
                                NewPartnerLocationRow.DateGoodUntil = CopyPartnerLocationRow.DateGoodUntil;
                            }
                        }

                        if (ADeleteDataRowCopiedFrom)
                        {
                            CopyPartnerLocationRow.Delete();
                            CopyPartnerLocationRow.AcceptChanges();
                        }
                    }
                    else
                    {
                        throw new ESecurityGroupAccessDeniedException(
                            "Address copying denied: " + "The Location Type of the Address that should be copied is '" +
                            CopyPartnerLocationRow.LocationType + "' but you are not in Security Group '" + SharedConstants.PETRAGROUP_ADDRESSCAN +
                            "'!");
                    }
                }
                else
                {
                    throw new ArgumentException("Row with specified ACopyFromFamilyPartnerKey cannot be found in PPartnerLocations DataTable!");
                }
            }
            else
            {
                NewPartnerLocationRow.LocationType = TSharedAddressHandling.GetDefaultLocationType(APartnerClass);
            }

            NewPartnerLocationRow.DateEffective = DateTime.Today;
            NewPartnerLocationRow.CreatedBy = UserInfo.GUserInfo.UserID;

            if (APartnerClass == TPartnerClass.PERSON)
            {
                NewPartnerLocationRow.SendMail = false;
            }
            else
            {
                NewPartnerLocationRow.SendMail = true;
            }

            APartnerLocationDT.Rows.Add(NewPartnerLocationRow);
        }
 /// <summary>
 /// </summary>
 /// <param name="ALocationDT"></param>
 /// <param name="APartnerLocationDT"></param>
 /// <param name="APartnerKey"></param>
 /// <param name="APartnerClass"></param>
 /// <param name="ACountryCode"></param>
 /// <param name="ANewLocationKey"></param>
 /// <param name="ACopyFromPartnerLocationKey"></param>
 public static void CreateNewAddressInternal(PLocationTable ALocationDT,
     PPartnerLocationTable APartnerLocationDT,
     Int64 APartnerKey,
     TPartnerClass APartnerClass,
     String ACountryCode,
     Int32 ANewLocationKey,
     Int32 ACopyFromPartnerLocationKey)
 {
     CreateNewAddressInternal(ALocationDT,
         APartnerLocationDT,
         APartnerKey,
         APartnerClass,
         ACountryCode,
         ANewLocationKey,
         ACopyFromPartnerLocationKey,
         -99,
         -1,
         -99,
         -99,
         false,
         true);
 }
        /// <summary>
        /// Determines the changes in the screen's dataset and submits them to the
        /// Server.
        /// </summary>
        /// <param name="AInspectDS">The screen's dataset
        /// </param>
        /// <returns>True if saving of data succeeded, otherwise false.</returns>
        private Boolean SaveChanges(ref PartnerEditTDS AInspectDS)
        {
            Boolean ReturnValue = false;
            PartnerEditTDS SubmitDS = null;
            TSubmitChangesResult SubmissionResult;

            TVerificationResultCollection VerificationResult;
            TVerificationResult VerificationResultItem;

            System.Windows.Forms.DialogResult UnitParentAssignment;
            int RowIndex;
            int NumRows;
            Int32 MaxColumn;
            Boolean SavedPartnerIsNewPartner = false;
            bool PartnerAttributesOrRelationsChanged = false;
            System.Int32 ChangedColumns;
#if SHOWCHANGES
            String DebugMessage;
#endif
#if DATASETDEBUGGING
            Int16 TmpRowCounter;
            string TmpDebugString = String.Empty;
#endif
            // Be sure to fire the OnLeave event on the active control of any user control
            FPetraUtilsObject.ForceOnLeaveForActiveControl();

            FPetraUtilsObject.OnDataSavingStart(this, new System.EventArgs());

            // Don't allow saving if user is still editing a Detail of a List
            if (FPetraUtilsObject.InDetailEditMode())
            {
                ReturnValue = false;
                return ReturnValue;
            }

            // Make sure that DataBinding writes the value of the active Control to the underlying DataSource!
            TDataBinding.EnsureDataChangesAreStored(this);

            GetDataFromControls();

            // Clear any validation errors so that the following call to ValidateAllData starts with a 'clean slate'.
            FPetraUtilsObject.VerificationResultCollection.Clear();

            if (ValidateAllData())
            {
                // Ask the user about non-critical warnings, if they are the only 'errors' in the collection
                if (FPetraUtilsObject.VerificationResultCollection.HasOnlyNonCriticalErrors
                    && (TDataValidation.ProcessAnyDataValidationWarnings(FPetraUtilsObject.VerificationResultCollection,
                            MCommonResourcestrings.StrFormSaveDataAnywayQuestion, this.GetType()) == false))
                {
                    return false;
                }

                // Fire the DataSavingValidated event, which is the last chance to cancel the save
                System.ComponentModel.CancelEventArgs eCancel = new System.ComponentModel.CancelEventArgs(false);
                FPetraUtilsObject.OnDataSavingValidated(this, eCancel);

                if (eCancel.Cancel == true)
                {
                    return false;
                }

                foreach (DataTable InspectDT in AInspectDS.Tables)
                {
                    foreach (DataRow InspectDR in InspectDT.Rows)
                    {
                        InspectDR.EndEdit();
                    }
                }

                if (FPetraUtilsObject.HasChanges)
                {
                    FPetraUtilsObject.WriteToStatusBar(MCommonResourcestrings.StrSavingDataInProgress);
                    this.Cursor = Cursors.WaitCursor;

                    /* $IFDEF SHOWCHANGES MessageBox.Show('SaveChanges: AInspectDS.PLocation.Rows[0].HasVersion(DataRowVersion.Original): ' + AInspectDS.PLocation.Rows[0].HasVersion(DataRowVersion.Original).ToString + '; LocationKey: ' +
                     *AInspectDS.PLocation.Row[0].LocationKey.ToString); $ENDIF */

                    /* $IFDEF SHOWCHANGES MessageBox.Show('SaveChanges: AInspectDS.PLocation.Rows[1].HasVersion(DataRowVersion.Original): ' + AInspectDS.PLocation.Rows[1].HasVersion(DataRowVersion.Original).ToString + '; LocationKey: ' +
                     *AInspectDS.PLocation.Row[1].LocationKey.ToString); $ENDIF */
                    if (!FPetraUtilsObject.SubmitChangesContinue)
                    {
                        foreach (DataTable InspectDT in AInspectDS.Tables)
                        {
                            // MessageBox.Show('inspectDataTable: ' + InspectDT.ToString);
                            if ((InspectDT.TableName != PLocationTable.GetTableName()) && (InspectDT.TableName != PPartnerLocationTable.GetTableName()))
                            {
                                MaxColumn = InspectDT.Columns.Count;
                                ChangedColumns = DataUtilities.AcceptChangesForUnmodifiedRows(InspectDT, MaxColumn);

                                if (ChangedColumns != 0)
                                {
#if SHOWCHANGES
                                    MessageBox.Show(InspectDT.TableName + " - changed colums: " + ChangedColumns.ToString());
#endif
                                }
                            }
                            else if (InspectDT.TableName == PLocationTable.GetTableName())
                            {
                                MaxColumn = new PLocationTable().Columns.Count;

                                // MessageBox.Show('PLocation MaxColumn: ' + MaxColumn.ToString);
                                ChangedColumns = DataUtilities.AcceptChangesForUnmodifiedRows(AInspectDS.PLocation, MaxColumn, true);

                                if (ChangedColumns != 0)
                                {
#if SHOWCHANGES
                                    MessageBox.Show(PLocationTable.GetTableName() + " - changed colums: " + ChangedColumns.ToString());
#endif
                                }
                            }
                            else
                            {
                                MaxColumn = new PPartnerLocationTable().Columns.Count;

                                // MessageBox.Show('PPartnerLocation MaxColumn: ' + MaxColumn.ToString);
                                ChangedColumns = DataUtilities.AcceptChangesForUnmodifiedRows(AInspectDS.PPartnerLocation,
                                    MaxColumn,
                                    true);

                                if (ChangedColumns != 0)
                                {
#if SHOWCHANGES
                                    MessageBox.Show(PPartnerLocationTable.GetTableName() + " - changed colums: " + ChangedColumns.ToString());
#endif
                                }
                            }

#if SHOWCHANGES
                            foreach (DataRow InspectDR in InspectDT.Rows)
                            {
                                DebugMessage = InspectDT.ToString();

                                if ((InspectDR.RowState == DataRowState.Modified) || (InspectDR.RowState == DataRowState.Added))
                                {
                                    ChangedColumns = 0;

                                    if (InspectDR.RowState == DataRowState.Modified)
                                    {
                                        DebugMessage = DebugMessage + " --- changed columns:" + Environment.NewLine;
                                    }
                                    else
                                    {
                                        DebugMessage = DebugMessage + " --- inserted Row. Column contents:" + Environment.NewLine;
                                    }

                                    for (int Counter1 = 0; Counter1 <= MaxColumn - 1; Counter1 += 1)
                                    {
                                        if ((InspectDR.RowState == DataRowState.Added) || (InspectDR != InspectDR[Counter1, DataRowVersion.Current]))
                                        {
                                            ChangedColumns = ChangedColumns + 1;
                                            DebugMessage = DebugMessage + "  " + (InspectDT.Columns[Counter1].ColumnName).ToString() + ": " +
                                                           InspectDR[Counter1, DataRowVersion.Current].ToString() + Environment.NewLine;
                                        }
                                    }

                                    if (ChangedColumns != 0)
                                    {
                                        MessageBox.Show(DebugMessage);
                                    }
                                    else
                                    {
                                        DebugMessage = DebugMessage + "  NO changed columns.";
                                        MessageBox.Show(DebugMessage);
                                    }
                                }
                                // (inspectDataRow.RowState = DataRowState.Modified) or (inspectDataRow.RowState = DataRowState.Added)
                                else
                                {
                                    // MessageBox.Show('inspectDataRow.RowState: ' + inspectDataRow.RowState.ToString("G"));
                                    if (InspectDR.RowState == DataRowState.Deleted)
                                    {
                                        DebugMessage = DebugMessage + " --- deleted Row. Original Column[0] contents: " +
                                                       InspectDR[0, DataRowVersion.Original].ToString();
                                        MessageBox.Show(DebugMessage);
                                    }
                                }
                            }
                            // for inspectDataRow in inspectDataTable.Rows do
#endif
                        }

                        // for inspectDataTable in inspectDataSet.Tables do
                    }

                    // If changes have been made to pm_staff_data (commitments) then update the partner's family's Gift Destination records
                    TGiftDestination GiftDestination = new TGiftDestination();

                    if (GiftDestination.UpdateGiftDestination(ref AInspectDS))
                    {
                        // set the gift destination on this screen and all other open partner edit screens for the same family
                        SetGiftDestinationAllScreens();
                    }

                    SubmitDS = AInspectDS.GetChangesTyped(true);

                    if (SubmitDS == null)
                    {
                        // There is nothing to be saved.
                        // Update UI
                        FPetraUtilsObject.WriteToStatusBar(MCommonResourcestrings.StrSavingDataNothingToSave);
                        this.Cursor = Cursors.Default;

                        // We don't have unsaved changes anymore
                        FPetraUtilsObject.DisableSaveButton();

                        return true;
                    }

                    if ((SubmitDS.Tables.Contains(PPartnerAttributeTable.GetTableName()))
                        || (SubmitDS.Tables.Contains(PPartnerRelationshipTable.GetTableName())))
                    {
                        PartnerAttributesOrRelationsChanged = true;
                    }

#if DATASETDEBUGGING
                    TLogging.Log("Before submitting data to the Server. Client DataSet: " + SubmitDS.GetXml());
#endif
                    // Submit changes to the PETRAServer
                    try
                    {
                        if (!FPetraUtilsObject.SubmitChangesContinue)
                        {
                            FResponseDS = null;
                            SubmissionResult = FPartnerEditUIConnector.SubmitChanges(ref SubmitDS, ref FResponseDS, out VerificationResult);
                        }
                        else
                        {
                            SubmissionResult = FPartnerEditUIConnector.SubmitChangesContinue(out SubmitDS, ref FResponseDS, out VerificationResult);
                        }
                    }
                    catch (ESecurityDBTableAccessDeniedException Exp)
                    {
                        FPetraUtilsObject.WriteToStatusBar(MCommonResourcestrings.StrSavingDataException);
                        this.Cursor = Cursors.Default;

                        TMessages.MsgSecurityException(Exp, this.GetType());

                        ReturnValue = false;
                        FPetraUtilsObject.OnDataSaved(this, new TDataSavedEventArgs(ReturnValue));
                        return ReturnValue;
                    }
                    catch (EDBConcurrencyException Exp)
                    {
                        FPetraUtilsObject.WriteToStatusBar(MCommonResourcestrings.StrSavingDataException);
                        this.Cursor = Cursors.Default;

                        TMessages.MsgDBConcurrencyException(Exp, this.GetType());

                        ReturnValue = false;
                        FPetraUtilsObject.OnDataSaved(this, new TDataSavedEventArgs(ReturnValue));
                        return ReturnValue;
                    }
                    catch (Exception)
                    {
                        FPetraUtilsObject.WriteToStatusBar(MCommonResourcestrings.StrSavingDataException);
                        this.Cursor = Cursors.Default;

                        FPetraUtilsObject.OnDataSaved(this, new TDataSavedEventArgs(ReturnValue));
                        throw;
                    }

                    switch (SubmissionResult)
                    {
                        case TSubmitChangesResult.scrOK:

                            SavedPartnerIsNewPartner = IsNewPartner(AInspectDS);

                            // MessageBox.Show('DUMMY: ' + (SubmitDS.Tables['Locations'].Rows[0]['DUMMY']).ToString() );
                            if ((SharedTypes.PartnerClassStringToEnum(AInspectDS.PPartner[0].PartnerClass) == TPartnerClass.UNIT)
                                && SavedPartnerIsNewPartner)
                            {
                                /*
                                 * A new Partner of PartnerClass UNIT has been created
                                 * -- give option to assign 'Parent' in Unit Hierarchy
                                 */
                                UnitParentAssignment = MessageBox.Show(StrQueryUnitParent,
                                    StrQueryUnitParentTitle,
                                    MessageBoxButtons.YesNo,
                                    MessageBoxIcon.Question,
                                    MessageBoxDefaultButton.Button1);

                                if (UnitParentAssignment == System.Windows.Forms.DialogResult.Yes)
                                {
                                    TFrmUnitHierarchy HierarchyForm = new TFrmUnitHierarchy(this.ParentForm);

                                    HierarchyForm.Show();
                                    HierarchyForm.ShowThisUnit(AInspectDS.PPartner[0].PartnerKey);
                                }
                            }

#if DATASETDEBUGGING
                            TLogging.Log("After submtting returned Server DataSet: " + SubmitDS.GetXml());
                            MessageBox.Show("Before CleanupAddressesBeforeMerge");
#endif
                            // Get rid of any new Addresses; they are returned back with different LocationKeys (based on a Sequence)
                            ucoLowerPart.CleanupAddressesBeforeMerge();
#if DATASETDEBUGGING
                            MessageBox.Show("After CleanupAddressesBeforeMerge");

                            if ((SubmitDS.PLocation != null)
                                && (SubmitDS.PLocation.Rows.Count > 0))
                            {
                                MessageBox.Show(
                                    "Location[0] LocationKey: " + SubmitDS.PLocation[0].LocationKey.ToString() +
                                    "; PartnerLocation[0] LocationKey: " +
                                    SubmitDS.PPartnerLocation[0].LocationKey.ToString());
                            }
#endif

                            // Delete all added Rows in the original dataset. They will automatically
                            // be put back in with the Merge. If added Rows are deleted they will
                            // be removed from the Row collection on the server. In that case the
                            // client will not be aware of that. For modified Rows: if they are
                            // deleted on the server they will not be taken out of the collection
                            // but come back to the client as being marked as 'Deleted'. Therefore
                            // with deleting the added Rows beforehand we are making sure that
                            // the dataset on the client is synchronized with the one on the server.
                            foreach (DataTable t in AInspectDS.Tables)
                            {
                                if ((t == AInspectDS.PBankingDetails)
                                    || (t == AInspectDS.PPartnerBankingDetails)
                                    || (t == AInspectDS.PDataLabelValuePartner))
                                {
                                    NumRows = t.Rows.Count;

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

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

                            // Update UserDefaults, if necessary
                            MaintainUserDefaults();

                            if (SubmitDS.Tables.Contains(PPartnerTaxDeductiblePctTable.GetTableName()))
                            {
                                UpdateTaxDeductiblePct();
                            }

                            // Call AcceptChanges to get rid now of any deleted columns before we Merge with the result from the Server
                            AInspectDS.AcceptChanges();
#if DATASETDEBUGGING
                            TLogging.Log("After getting rid now of any deleted columns   Client DataSet: " + AInspectDS.GetXml());

                            if (AInspectDS.Tables.Contains(PLocationTable.GetTableName()))
                            {
                                for (TmpRowCounter = 0; TmpRowCounter < AInspectDS.Tables[PLocationTable.GetTableName()].Rows.Count; TmpRowCounter++)
                                {
                                    TmpDebugString = TmpDebugString + PLocationTable.GetTableName() + ".Row[" + TmpRowCounter.ToString() +
                                                     "]: PLocationKey: " +
                                                     AInspectDS.Tables[PLocationTable.GetTableName()].Rows[TmpRowCounter][PLocationTable.
                                                                                                                          GetLocationKeyDBName()].
                                                     ToString() + "(); PSiteKey: " +
                                                     AInspectDS.Tables[PLocationTable.GetTableName()].Rows[TmpRowCounter][PLocationTable.
                                                                                                                          GetSiteKeyDBName()].
                                                     ToString() + "(); Modification TimeStamp: " +
                                                     AInspectDS.Tables[PLocationTable.GetTableName()].Rows[TmpRowCounter][PLocationTable.
                                                                                                                          GetModificationIdDBName()].
                                                     ToString() + "\r\n";
                                }
                            }

                            if (AInspectDS.Tables.Contains(PPartnerLocationTable.GetTableName()))
                            {
                                TmpDebugString = TmpDebugString + "\r\n";

                                for (TmpRowCounter = 0;
                                     TmpRowCounter < AInspectDS.Tables[PPartnerLocationTable.GetTableName()].Rows.Count;
                                     TmpRowCounter++)
                                {
                                    TmpDebugString = TmpDebugString + PPartnerLocationTable.GetTableName() + ".Row[" + TmpRowCounter.ToString() +
                                                     "]: PLocationKey: " +
                                                     AInspectDS.Tables[PPartnerLocationTable.GetTableName()].Rows[TmpRowCounter][
                                        PPartnerLocationTable.GetLocationKeyDBName()].ToString() + "(); PSiteKey: " +
                                                     AInspectDS.Tables[PPartnerLocationTable.GetTableName()].Rows[TmpRowCounter][
                                        PPartnerLocationTable.GetSiteKeyDBName()].ToString() + "(); PPartnerKey: " +
                                                     AInspectDS.Tables[PPartnerLocationTable.GetTableName()].Rows[TmpRowCounter][
                                        PPartnerLocationTable.GetPartnerKeyDBName()].ToString() + "(); Modification TimeStamp: " +
                                                     AInspectDS.Tables[PPartnerLocationTable.GetTableName()].Rows[TmpRowCounter][
                                        PPartnerLocationTable.GetModificationIdDBName()].ToString() + "\r\n";
                                }

                                MessageBox.Show(TmpDebugString, "DEBUG: PLocation / PPartnerLocation local contents  [#1]");
                            }
#endif
                            // Merge back with data from the Server (eg. for getting Sequence values)
                            AInspectDS.Merge(SubmitDS, false);
#if DATASETDEBUGGING
                            TLogging.Log("After Merge back with data from the Server  Server DataSet: " + SubmitDS.GetXml());
                            TLogging.Log("After Merge back with data from the Server  Client DataSet: " + AInspectDS.GetXml());

                            if (AInspectDS.Tables.Contains(PLocationTable.GetTableName()))
                            {
                                TmpDebugString = "";

                                for (TmpRowCounter = 0; TmpRowCounter < AInspectDS.Tables[PLocationTable.GetTableName()].Rows.Count; TmpRowCounter++)
                                {
                                    TmpDebugString = TmpDebugString + PLocationTable.GetTableName() + ".Row[" + TmpRowCounter.ToString() +
                                                     "]: PLocationKey: " +
                                                     AInspectDS.Tables[PLocationTable.GetTableName()].Rows[TmpRowCounter][PLocationTable.
                                                                                                                          GetLocationKeyDBName()].
                                                     ToString() + "(); PSiteKey: " +
                                                     AInspectDS.Tables[PLocationTable.GetTableName()].Rows[TmpRowCounter][PLocationTable.
                                                                                                                          GetSiteKeyDBName()].
                                                     ToString() + "(); Modification TimeStamp: " +
                                                     AInspectDS.Tables[PLocationTable.GetTableName()].Rows[TmpRowCounter][PLocationTable.
                                                                                                                          GetModificationIdDBName()].
                                                     ToString() + "\r\n";
                                }
                            }

                            if (AInspectDS.Tables.Contains(PPartnerLocationTable.GetTableName()))
                            {
                                TmpDebugString = TmpDebugString + "\r\n";

                                for (TmpRowCounter = 0;
                                     TmpRowCounter < AInspectDS.Tables[PPartnerLocationTable.GetTableName()].Rows.Count;
                                     TmpRowCounter++)
                                {
                                    TmpDebugString = TmpDebugString + PPartnerLocationTable.GetTableName() + ".Row[" + TmpRowCounter.ToString() +
                                                     "]: PLocationKey: " +
                                                     AInspectDS.Tables[PPartnerLocationTable.GetTableName()].Rows[TmpRowCounter][
                                        PPartnerLocationTable.GetLocationKeyDBName()].ToString() + "(); PSiteKey: " +
                                                     AInspectDS.Tables[PPartnerLocationTable.GetTableName()].Rows[TmpRowCounter][
                                        PPartnerLocationTable.GetSiteKeyDBName()].ToString() + "(); PPartnerKey: " +
                                                     AInspectDS.Tables[PPartnerLocationTable.GetTableName()].Rows[TmpRowCounter][
                                        PPartnerLocationTable.GetPartnerKeyDBName()].ToString() + "(); Modification TimeStamp: " +
                                                     AInspectDS.Tables[PPartnerLocationTable.GetTableName()].Rows[TmpRowCounter][
                                        PPartnerLocationTable.GetModificationIdDBName()].ToString() + "\r\n";
                                }

                                MessageBox.Show(TmpDebugString, "DEBUG: PLocation / PPartnerLocation local contents  [#2]");
                            }
#endif

                            ucoUpperPart.UpdateStatusUpdatedDate();  // this is to refresh 'Status Updated' if it has been changed in the ComboBox and then saved...

                            ucoLowerPart.RefreshRecordsAfterMerge();
                            ucoLowerPart.RefreshPersonnelDataAfterMerge(PartnerAttributesOrRelationsChanged);

                            // Call AcceptChanges so that we don't have any changed data anymore!
                            AInspectDS.AcceptChanges();
#if DATASETDEBUGGING
                            TLogging.Log("After calling AcceptChanges on the Client DataSet: " + AInspectDS.GetXml());
#endif
                            // Update UI
                            FPetraUtilsObject.WriteToStatusBar(MCommonResourcestrings.StrSavingDataSuccessful);
                            this.Cursor = Cursors.Default;
                            EnableSave(false);

                            // If the screen was opened for a NEW Partner, remove the 'NEW:' indicator from the Window Title Bar and
                            // set this Partner to be the "Last Used Partner".
                            if (SavedPartnerIsNewPartner)
                            {
                                FPetraUtilsObject.HasNewData = false;
                                SetScreenCaption();

                                // Set Partner to be the "Last Used Partner"
                                TUserDefaults.NamedDefaults.SetLastPartnerWorkedWith(AInspectDS.PPartner[0].PartnerKey,
                                    TLastPartnerUse.lpuMailroomPartner, SharedTypes.PartnerClassStringToEnum(FPartnerClass));
                            }

                            // We don't have unsaved changes anymore
                            FPetraUtilsObject.DisableSaveButton();
                            FPetraUtilsObject.SubmitChangesContinue = false;

                            // Assign PartnerKey. This is needed in case this was a new Partner before saving!
                            FPartnerKey = AInspectDS.PPartner[0].PartnerKey;

                            ReturnValue = true;
                            FPetraUtilsObject.OnDataSaved(this, new TDataSavedEventArgs(ReturnValue));

                            if ((VerificationResult != null)
                                && (VerificationResult.HasCriticalOrNonCriticalErrors))
                            {
                                TDataValidation.ProcessAnyDataValidationErrors(false, VerificationResult,
                                    this.GetType(), null);
                            }

                            break;

                        case TSubmitChangesResult.scrError:
                            this.Cursor = Cursors.Default;

                            if (!(VerificationResult.Contains((System.Object) "Location Change Promotion: Information")))
                            {
                                FPetraUtilsObject.WriteToStatusBar(MCommonResourcestrings.StrSavingDataErrorOccured);

                                TDataValidation.ProcessAnyDataValidationErrors(false, VerificationResult,
                                    this.GetType(), null);
                            }
                            else
                            {
                                FPetraUtilsObject.WriteToStatusBar(MCommonResourcestrings.StrSavingDataCancelled);

                                VerificationResultItem = (TVerificationResult)VerificationResult.FindBy(
                                    (object)"Location Change Promotion: Information");

                                MessageBox.Show(VerificationResultItem.ResultText,
                                    VerificationResultItem.ResultTextCaption, MessageBoxButtons.OK,
                                    MessageBoxIcon.Information);
                            }

                            FPetraUtilsObject.SubmitChangesContinue = false;

                            ReturnValue = false;
                            FPetraUtilsObject.OnDataSaved(this, new TDataSavedEventArgs(ReturnValue));
                            break;

                        case TSubmitChangesResult.scrNothingToBeSaved:

                            // If there were no changes discovered then still need to call AcceptChanges to get rid now of
                            // any deleted columns
                            AInspectDS.AcceptChanges();

                            // Update UI
                            this.Cursor = Cursors.Default;
                            FPetraUtilsObject.WriteToStatusBar(MCommonResourcestrings.StrSavingDataNothingToSave);

                            // We don't have unsaved changes anymore
                            EnableSave(false);
                            FPetraUtilsObject.HasChanges = false;

                            ReturnValue = true;
                            FPetraUtilsObject.OnDataSaved(this, new TDataSavedEventArgs(ReturnValue));
                            break;

                        case TSubmitChangesResult.scrInfoNeeded:
                            this.Cursor = Cursors.Default;
#if DATASETDEBUGGING
                            for (int Counter2 = 0; Counter2 < FResponseDS.Tables.Count; Counter2++)
                            {
                                MessageBox.Show(
                                    "Table #" + Counter2.ToString() + "'s name is " + FResponseDS.Tables[Counter2].TableName + ". It has " +
                                    FResponseDS.Tables[Counter2].Rows.Count.ToString() + " Rows. Type: " +
                                    FResponseDS.Tables[Counter2].GetType().ToString());
                            }

                            if (FResponseDS.Tables.Contains(MPartnerConstants.EXISTINGLOCATIONPARAMETERS_TABLENAME))
                            {
                                MessageBox.Show("FResponseDS Type: " + FResponseDS.GetType().ToString());
                                MessageBox.Show(MPartnerConstants.EXISTINGLOCATIONPARAMETERS_TABLENAME + " Type: " +
                                    FResponseDS.Tables[MPartnerConstants.EXISTINGLOCATIONPARAMETERS_TABLENAME].GetType().ToString());
                                MessageBox.Show(
                                    "FResponseDS.Tables[" + MPartnerConstants.EXISTINGLOCATIONPARAMETERS_TABLENAME + "].Rows.Count: " +
                                    FResponseDS.Tables[MPartnerConstants.EXISTINGLOCATIONPARAMETERS_TABLENAME].Rows.Count.ToString());
                                // Check if there is a Parameter Row that is not yet processed
                                DataView ExistingLocationParametersDV = new DataView(
                                    FResponseDS.Tables[MPartnerConstants.EXISTINGLOCATIONPARAMETERS_TABLENAME],
                                    PartnerAddressAggregateTDSSimilarLocationParametersTable.GetAnswerProcessedClientSideDBName() +
                                    " = false", "", DataViewRowState.CurrentRows);

                                if (ExistingLocationParametersDV.Count > 0)
                                {
                                    MessageBox.Show("ExistingLocationParametersDV.Count: " + ExistingLocationParametersDV.Count.ToString());
                                    MessageBox.Show(
                                        "Row[0].LocationKey: " +
                                        (ExistingLocationParametersDV[0].Row as PartnerAddressAggregateTDSSimilarLocationParametersRow).LocationKey.
                                        ToString());
                                }
                            }
#endif
                            ucoLowerPart.SimilarLocationsProcessing(
                            (PartnerAddressAggregateTDSSimilarLocationParametersTable)FResponseDS.Tables[MPartnerConstants.
                                                                                                         EXISTINGLOCATIONPARAMETERS_TABLENAME]);
#if DATASETDEBUGGING
                            if (FResponseDS.Tables[MPartnerConstants.EXISTINGLOCATIONPARAMETERS_TABLENAME].Rows.Count > 0)
                            {
                                MessageBox.Show("Reuse?: " + (FResponseDS.Tables[MPartnerConstants.EXISTINGLOCATIONPARAMETERS_TABLENAME]
                                                              as PartnerAddressAggregateTDSSimilarLocationParametersTable)[0].AnswerReuse.ToString());
                            }

                            if (FResponseDS.Tables.Contains(MPartnerConstants.ADDRESSADDEDORCHANGEDPROMOTION_TABLENAME))
                            {
                                MessageBox.Show(MPartnerConstants.ADDRESSADDEDORCHANGEDPROMOTION_TABLENAME + " Type: " +
                                    FResponseDS.Tables[MPartnerConstants.ADDRESSADDEDORCHANGEDPROMOTION_TABLENAME].GetType().ToString());
                                MessageBox.Show(
                                    "FResponseDS.Tables[" + MPartnerConstants.ADDRESSADDEDORCHANGEDPROMOTION_TABLENAME + "].Rows.Count: " +
                                    FResponseDS.Tables[MPartnerConstants.ADDRESSADDEDORCHANGEDPROMOTION_TABLENAME].Rows.Count.ToString());
                                //Check if there is a Parameter Row that is not yet processed
                                DataView AddressAddedOrChangedParametersDV = new DataView(
                                    FResponseDS.Tables[MPartnerConstants.ADDRESSADDEDORCHANGEDPROMOTION_TABLENAME],
                                    PartnerAddressAggregateTDSAddressAddedOrChangedPromotionTable.GetAnswerProcessedClientSideDBName() +
                                    " = false", "", DataViewRowState.CurrentRows);

                                if (AddressAddedOrChangedParametersDV.Count > 0)
                                {
                                    MessageBox.Show("AddressAddedOrChangedParametersDV.Count: " + AddressAddedOrChangedParametersDV.Count.ToString());
                                    MessageBox.Show(
                                        "Row[0].LocationKey: " +
                                        (AddressAddedOrChangedParametersDV[0].Row as PartnerAddressAggregateTDSAddressAddedOrChangedPromotionRow).
                                        LocationKey.
                                        ToString());
                                }
                            }
#endif
                            ucoLowerPart.AddressAddedOrChangedProcessing(
                            (PartnerAddressAggregateTDSAddressAddedOrChangedPromotionTable)
                            FResponseDS.Tables[MPartnerConstants.ADDRESSADDEDORCHANGEDPROMOTION_TABLENAME],
                            (PartnerAddressAggregateTDSChangePromotionParametersTable)
                            FResponseDS.Tables[MPartnerConstants.ADDRESSCHANGEPROMOTIONPARAMETERS_TABLENAME]);
#if DATASETDEBUGGING
                            MessageBox.Show("After AddressAddedOrChangedProcessing");
#endif
                            // Recursive call!
                            FPetraUtilsObject.SubmitChangesContinue = true;
                            ReturnValue = SaveChanges(ref AInspectDS);

                            return ReturnValue;
                    }
                }
                else
                {
                    // Update UI
                    FPetraUtilsObject.WriteToStatusBar(MCommonResourcestrings.StrSavingDataNothingToSave);
                    this.Cursor = Cursors.Default;
                    EnableSave(false);

                    // We don't have unsaved changes anymore
                    FPetraUtilsObject.HasChanges = false;

                    ReturnValue = true;
                    FPetraUtilsObject.OnDataSaved(this, new TDataSavedEventArgs(ReturnValue));
                }
            }
            else
            {
                FPetraUtilsObject.OnDataSaved(this, new TDataSavedEventArgs(false));
            }

            // if the partner has been saved then broadcast a message to any listening forms to inform them
            if (ReturnValue)
            {
                TFormsMessage BroadcastMessage;
                TFormsMessage BroadcastMessageGiftDestination;
                String PartnerShortNameForBroadcast;
                long FamilyPartnerKey;
                String FamilyShortName;

                if (SavedPartnerIsNewPartner)
                {
                    BroadcastMessage = new TFormsMessage(TFormsMessageClassEnum.mcNewPartnerSaved,
                        FCallerContext);
                }
                else
                {
                    BroadcastMessage = new TFormsMessage(TFormsMessageClassEnum.mcExistingPartnerSaved,
                        FCallerContext);
                }

                if (!FMainDS.PPartner[0].IsPartnerShortNameNull())
                {
                    PartnerShortNameForBroadcast = FMainDS.PPartner[0].PartnerShortName;
                }
                else
                {
                    PartnerShortNameForBroadcast = String.Empty;
                }

                BroadcastMessage.SetMessageDataPartner(
                    FPartnerKey,
                    SharedTypes.PartnerClassStringToEnum(FPartnerClass),
                    PartnerShortNameForBroadcast,
                    FMainDS.PPartner[0].StatusCode);

                TFormsList.GFormsList.BroadcastFormMessage(BroadcastMessage);

                if ((SubmitDS.PPartnerGiftDestination != null) && (SubmitDS.PPartnerGiftDestination.Rows.Count > 0))
                {
                    BroadcastMessageGiftDestination = new TFormsMessage(TFormsMessageClassEnum.mcPersonnelCommitmentChanged,
                        FCallerContext);

                    if (FPartnerClass == TPartnerClass.FAMILY.ToString())
                    {
                        FamilyPartnerKey = FPartnerKey;
                        FamilyShortName = PartnerShortNameForBroadcast;
                    }
                    else
                    {
                        FamilyPartnerKey = ((PPersonRow)FMainDS.PPerson.Rows[0]).FamilyKey;
                        FamilyShortName = String.Empty;
                    }

                    BroadcastMessageGiftDestination.SetMessageDataPartner(
                        FamilyPartnerKey,
                        TPartnerClass.FAMILY,
                        FamilyShortName,
                        FMainDS.PPartner[0].StatusCode);

                    TFormsList.GFormsList.BroadcastFormMessage(BroadcastMessageGiftDestination);
                }
            }

            return ReturnValue;
        }
        private void BtnOK_Click(System.Object sender, EventArgs e)
        {
            if (clbAddress.CheckedItemsCount == 0)
            {
                FUserAnswer = "CHANGE-NONE";
            }
            else if (clbAddress.CheckedItemsCount == FPartnerSharingLocationDV.Count)
            {
                FUserAnswer = "CHANGE-ALL";
            }
            else
            {
                FUserAnswer = "CHANGE-SOME" + ':';

                FUserAnswer = FUserAnswer + clbAddress.GetCheckedStringList();

                // return list separated by ';'
                FUserAnswer.Replace(',', ';');
            }

            //MessageBox.Show("FUserAnswer: " + FUserAnswer);

            if ((FUserAnswer == "CHANGE-NONE") || (FUserAnswer.StartsWith("CHANGE-SOME")))
            {
                /* Check whether user has CREATE right on p_location table */
                if (!UserInfo.GUserInfo.IsTableAccessOK(TTableAccessPermission.tapCREATE, PLocationTable.GetTableDBName()))
                {
                    TMessages.MsgSecurityException(new ESecurityDBTableAccessDeniedException("", "create",
                                                                                             PLocationTable.GetTableDBName()), this.GetType());
                    MessageBox.Show(Catalog.GetString("Due to the selection that you have made" + " a new Address would need" + "\r\n" +
                                                      "to be created. However, you do not have permission to do this." + "\r\n" + "\r\n" +
                                                      "Either select 'Change all' to change all addresses (if this is appropriate)," +
                                                      "\r\n" + "or choose 'Cancel' to abort the Save operation."),
                                    Catalog.GetString("Security Violation - Explanation"),
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Warning);
                    return;
                }
                else
                {
                    DialogResult = System.Windows.Forms.DialogResult.OK;
                }
            }
            else
            {
                DialogResult = System.Windows.Forms.DialogResult.OK;
            }

            Close();
        }
        private PartnerEditTDSPPartnerLocationTable GetPartnerLocationsInternal(out Int32 ACount, Boolean ACountOnly, ref PLocationTable ALocations)
        {
            TDBTransaction ReadTransaction;
            Boolean NewTransaction = false;
            PartnerEditTDS PartnerLocations = new PartnerEditTDS();
            PLocationTable LocationTable;
            PLocationRow LocationRow;

            try
            {
                ReadTransaction = DBAccess.GDBAccessObj.GetNewOrExistingTransaction(IsolationLevel.RepeatableRead,
                    TEnforceIsolationLevel.eilMinimum,
                    out NewTransaction);

                if (ACountOnly)
                {
                    ACount = PPartnerLocationAccess.CountViaPPartner(FPartnerKey, ReadTransaction);
                }
                else
                {
                    // Logging.LogAtLevel(7,  "TPartnerEditUIConnector.GetPartnerLocationsInternal: loading Locations for Partner " + FPartnerKey.ToString() + "...");
                    try
                    {
                        ALocations = PLocationAccess.LoadViaPPartner(FPartnerKey, ReadTransaction);

                        PPartnerLocationAccess.LoadViaPPartner(PartnerLocations, FPartnerKey, ReadTransaction);

                        foreach (PartnerEditTDSPPartnerLocationRow row in PartnerLocations.PPartnerLocation.Rows)
                        {
                            LocationTable = PLocationAccess.LoadByPrimaryKey(row.SiteKey, row.LocationKey, ReadTransaction);

                            if (LocationTable.Count > 0)
                            {
                                LocationRow = LocationTable[0];

                                row.LocationLocality = LocationRow.Locality;
                                row.LocationStreetName = LocationRow.StreetName;
                                row.LocationAddress3 = LocationRow.Address3;
                                row.LocationCity = LocationRow.City;
                                row.LocationCounty = LocationRow.County;
                                row.LocationPostalCode = LocationRow.PostalCode;
                                row.LocationCountryCode = LocationRow.CountryCode;

                                row.LocationCreatedBy = LocationRow.CreatedBy;

                                if (!LocationRow.IsDateCreatedNull())
                                {
                                    row.LocationDateCreated = LocationRow.DateCreated.Value;
                                }

                                row.LocationModifiedBy = LocationRow.ModifiedBy;

                                if (!LocationRow.IsDateModifiedNull())
                                {
                                    row.LocationDateModified = LocationRow.DateModified.Value;
                                }
                            }
                        }
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                    ACount = PartnerLocations.PPartnerLocation.Rows.Count;
                }
            }
            finally
            {
                if (NewTransaction)
                {
                    DBAccess.GDBAccessObj.CommitTransaction();
                    TLogging.LogAtLevel(7, "TPartnerEditUIConnector.GetPartnerLocationsInternal: committed own transaction.");
                }
            }
            return PartnerLocations.PPartnerLocation;
        }
        /// <summary>
        /// todoComment
        /// </summary>
        /// <returns></returns>
        public PartnerEditTDSPPartnerLocationTable GetDataPartnerLocations(ref PLocationTable ALocations)
        {
            Int32 LocationsCount;

            return GetPartnerLocationsInternal(out LocationsCount, false, ref ALocations);
        }
 /// <summary>
 /// Creates a new DataRow in the passed PLocation and PPartnerLocation tables.
 /// </summary>
 /// <param name="ALocationDT">Typed PLocation table. If null is passed in it is created
 /// automatically</param>
 /// <param name="APartnerLocationDT">Typed PPartnerLocation table. If null is passed in
 /// it is created automatically</param>
 /// <param name="APartnerKey">PartneKey of the Partner for which the Address should
 /// be created</param>
 /// <param name="APartnerClass">PartnerClass of the Partner for which the Address should
 /// be created</param>
 /// <param name="ACountryCode"></param>
 /// <param name="ANewLocationKey">A LocationKey that the new Location and
 /// PartnerLocation rows would be set to.</param>
 /// <param name="ACopyFromFamilyPartnerKey">Pass in the PartnerKey of a Family Partner
 /// to copy over all data from the Family's Address. Note: the DataRow
 /// specified with ACopyFromFamilyPartnerKey must be present in the
 /// APartnerLocationDT table!</param>
 /// <param name="ACopyFromFamilyLocationKey">Pass in the LocationKey of the Family
 /// Partner specified in ACopyFromFamilyPartnerKey to copy over all data from
 /// the Family's Address. Note: the DataRow specified with
 /// ACopyFromFamilyLocationKey must be present in both the ALocationDT and
 /// APartnerLocationDT table!</param>
 /// <param name="ACopyFromFamilySiteKey">A SiteKey to find the location that should be the source of the copy</param>
 /// <param name="ACopyFromFamilyOnlyLocation"></param>
 /// <param name="ADeleteDataRowCopiedFrom"></param>
 /// <exception cref="ArgumentException"> if any of the Arguments (or their combination) is
 /// not valid.</exception>
 public static void CreateNewAddress(PLocationTable ALocationDT,
     PPartnerLocationTable APartnerLocationDT,
     Int64 APartnerKey,
     TPartnerClass APartnerClass,
     String ACountryCode,
     Int32 ANewLocationKey,
     Int64 ACopyFromFamilyPartnerKey,
     Int32 ACopyFromFamilyLocationKey,
     Int64 ACopyFromFamilySiteKey,
     Boolean ACopyFromFamilyOnlyLocation,
     Boolean ADeleteDataRowCopiedFrom)
 {
     CreateNewAddressInternal(ALocationDT,
         APartnerLocationDT,
         APartnerKey,
         APartnerClass,
         ACountryCode,
         ANewLocationKey,
         ACopyFromFamilyPartnerKey,
         ACopyFromFamilyLocationKey,
         ACopyFromFamilySiteKey,
         ACopyFromFamilyOnlyLocation,
         ADeleteDataRowCopiedFrom);
 }
Exemple #40
0
        /// <summary>
        /// this will find the best p_partner_location, and export the values to parameters (p_street_name_c, etc.)
        /// </summary>
        /// <returns>void</returns>
        private bool GetPartnerBestAddress(Int64 APartnerKey)
        {
            bool ReturnValue = false;

            // reset the variables
            PLocationTable LocationTable = new PLocationTable();

            foreach (DataColumn col in LocationTable.Columns)
            {
                situation.GetParameters().RemoveVariable(StringHelper.UpperCamelCase(col.ColumnName, true, true));
            }

            DataTable PartnerLocationTable = new PPartnerLocationTable();

            foreach (DataColumn col in PartnerLocationTable.Columns)
            {
                // do not clear the partner key, in case we do not have an address for the partner
                if (col.ColumnName != PPartnerLocationTable.GetPartnerKeyDBName())
                {
                    situation.GetParameters().RemoveVariable(StringHelper.UpperCamelCase(col.ColumnName, true, true));
                }
            }

            situation.GetParameters().RemoveVariable("FirstName");
            situation.GetParameters().RemoveVariable("FamilyName");

            StringCollection NameColumnNames = new StringCollection();
            NameColumnNames.Add(PPartnerTable.GetPartnerShortNameDBName());
            PPartnerTable PartnerTable = PPartnerAccess.LoadByPrimaryKey(APartnerKey, NameColumnNames,
                situation.GetDatabaseConnection().Transaction);
            string PartnerShortName = PartnerTable.Rows[0][PPartnerTable.GetPartnerShortNameDBName()].ToString();

            situation.GetParameters().AddCalculationParameter("NameWithTitle",
                new TVariant(Ict.Petra.Shared.MPartner.Calculations.FormatShortName(PartnerShortName, eShortNameFormat.eReverseShortname)));

            DataSet PartnerLocationsDS = new DataSet();
            PartnerLocationsDS.Tables.Add(new PPartnerLocationTable());
            PartnerLocationTable = PartnerLocationsDS.Tables[PPartnerLocationTable.GetTableName()];

            // add special column BestAddress and Icon
            PartnerLocationTable.Columns.Add(new System.Data.DataColumn("BestAddress", typeof(Boolean)));
            PartnerLocationTable.Columns.Add(new System.Data.DataColumn("Icon", typeof(Int32)));

            // find all locations of the partner, put it into a dataset
            PPartnerLocationAccess.LoadViaPPartner(PartnerLocationsDS, APartnerKey, situation.GetDatabaseConnection().Transaction);

            // uses Ict.Petra.Shared.MPartner.Calculations.pas, DetermineBestAddress
            Calculations.DeterminePartnerLocationsDateStatus(PartnerLocationsDS);
            Calculations.DetermineBestAddress(PartnerLocationsDS);

            foreach (PPartnerLocationRow row in PartnerLocationTable.Rows)
            {
                // find the row with BestAddress = 1
                if (Convert.ToInt32(row["BestAddress"]) == 1)
                {
                    // find the location record with that address
                    LocationTable = PLocationAccess.LoadByPrimaryKey(row.SiteKey, row.LocationKey, situation.GetDatabaseConnection().Transaction);

                    // put the found values in the parameters
                    if (LocationTable.Rows.Count > 0)
                    {
                        // get the location details into the parameters
                        foreach (DataColumn col in LocationTable.Columns)
                        {
                            situation.GetParameters().AddCalculationParameter(StringHelper.UpperCamelCase(col.ColumnName, true,
                                    true), new TVariant(LocationTable.Rows[0][col.ColumnName]));
                        }

                        // also put the phone number and email etc into the parameters
                        foreach (DataColumn col in PartnerLocationTable.Columns)
                        {
                            situation.GetParameters().AddCalculationParameter(StringHelper.UpperCamelCase(col.ColumnName, true,
                                    true), new TVariant(row[col.ColumnName]));
                        }

                        // get the Partner Firstname and Surname as well; depends on the partner class
                        // first try person
                        NameColumnNames = new StringCollection();
                        NameColumnNames.Add(PPersonTable.GetFirstNameDBName());
                        NameColumnNames.Add(PPersonTable.GetFamilyNameDBName());
                        PPersonTable PersonTable = PPersonAccess.LoadByPrimaryKey(APartnerKey, NameColumnNames,
                            situation.GetDatabaseConnection().Transaction);

                        if (PersonTable.Rows.Count > 0)
                        {
                            situation.GetParameters().AddCalculationParameter("FirstName",
                                new TVariant(PersonTable.Rows[0][PPersonTable.GetFirstNameDBName()]));
                            situation.GetParameters().AddCalculationParameter("FamilyName",
                                new TVariant(PersonTable.Rows[0][PPersonTable.GetFamilyNameDBName()]));
                        }
                        else
                        {
                            // then it was a family?
                            NameColumnNames = new StringCollection();
                            NameColumnNames.Add(PFamilyTable.GetFirstNameDBName());
                            NameColumnNames.Add(PFamilyTable.GetFamilyNameDBName());
                            PFamilyTable FamilyTable = PFamilyAccess.LoadByPrimaryKey(APartnerKey, NameColumnNames,
                                situation.GetDatabaseConnection().Transaction);

                            if (FamilyTable.Rows.Count > 0)
                            {
                                situation.GetParameters().AddCalculationParameter("FirstName",
                                    new TVariant(FamilyTable.Rows[0][PFamilyTable.GetFirstNameDBName()]));
                                situation.GetParameters().AddCalculationParameter("FamilyName",
                                    new TVariant(FamilyTable.Rows[0][PFamilyTable.GetFamilyNameDBName()]));
                            }
                            else
                            {
                                // it was an organisation or church, just use the shortname
                                situation.GetParameters().RemoveVariable("FirstName");
                                situation.GetParameters().RemoveVariable("FamilyName");

                                if (PartnerTable.Rows.Count > 0)
                                {
                                    situation.GetParameters().AddCalculationParameter("FamilyName",
                                        new TVariant(PartnerShortName));
                                }
                            }
                        }

                        ReturnValue = true;
                    }
                }
            }

            return ReturnValue;
        }
Exemple #41
0
        /// <summary>
        /// get the best email address that is valid today, with some location details
        /// </summary>
        public static string GetBestEmailAddressWithDetails(Int64 APartnerKey, out PLocationTable AAddress, out string ACountryNameLocal)
        {
            string EmailAddress = "";
            PLocationTable Address = null;
            string CountryNameLocal = "";
            TDBTransaction Transaction = null;

            DBAccess.GDBAccessObj.GetNewOrExistingAutoReadTransaction(IsolationLevel.ReadCommitted, ref Transaction,
                delegate
                {
                    DataSet PartnerLocationsDS = new DataSet();

                    PartnerLocationsDS.Tables.Add(new PPartnerLocationTable());
                    PartnerLocationsDS.Tables.Add(new PCountryTable());
                    DataTable PartnerLocationTable = PartnerLocationsDS.Tables[PPartnerLocationTable.GetTableName()];
                    PCountryTable CountryTable = (PCountryTable)PartnerLocationsDS.Tables[PCountryTable.GetTableName()];
                    CountryTable.DefaultView.Sort = PCountryTable.GetCountryCodeDBName();

                    // add special column BestAddress and Icon
                    PartnerLocationTable.Columns.Add(new System.Data.DataColumn("BestAddress", typeof(Boolean)));
                    PartnerLocationTable.Columns.Add(new System.Data.DataColumn("Icon", typeof(Int32)));

                    // find all locations of the partner, put it into a dataset
                    PPartnerLocationAccess.LoadViaPPartner(PartnerLocationsDS, APartnerKey, Transaction);

                    Ict.Petra.Shared.MPartner.Calculations.DeterminePartnerLocationsDateStatus(PartnerLocationsDS);
                    Ict.Petra.Shared.MPartner.Calculations.DetermineBestAddress(PartnerLocationsDS);

                    foreach (PPartnerLocationRow row in PartnerLocationTable.Rows)
                    {
                        // find the row with BestAddress = 1
                        if (Convert.ToInt32(row["BestAddress"]) == 1)
                        {
                            if (!row.IsEmailAddressNull())
                            {
                                EmailAddress = row.EmailAddress;
                            }

                            // we also want the post address, need to load the p_location table:
                            Address = PLocationAccess.LoadByPrimaryKey(row.SiteKey, row.LocationKey, Transaction);

                            if (CountryTable.DefaultView.Find(Address[0].CountryCode) == -1)
                            {
                                CountryTable.Merge(PCountryAccess.LoadByPrimaryKey(Address[0].CountryCode, Transaction));
                            }

                            CountryNameLocal = CountryTable[CountryTable.DefaultView.Find(Address[0].CountryCode)].CountryNameLocal;
                        }
                    }
                });

            AAddress = Address;
            ACountryNameLocal = CountryNameLocal;

            return EmailAddress;
        }
        /// <summary>
        /// Used internally to build a SQL WHERE criteria from the AFindCriteria HashTable.
        ///
        /// </summary>
        /// <param name="ACriteriaData">HashTable containing non-empty Partner Find parameters</param>
        /// <param name="AParametersArray">An array holding 1..n instantiated OdbcParameters
        /// (including parameter Value)</param>
        /// <returns>SQL WHERE criteria
        /// </returns>
        private String BuildCustomWhereCriteria(DataTable ACriteriaData, out OdbcParameter[] AParametersArray)
        {
            String        CustomWhereCriteria = "";
            DataTable     CriteriaDataTable;
            DataRow       CriteriaRow;
            ArrayList     InternalParameters;
            OdbcParameter miParam;

            CriteriaDataTable  = ACriteriaData;
            CriteriaRow        = CriteriaDataTable.Rows[0];
            InternalParameters = new ArrayList();

            if (CriteriaRow["Addr1"].ToString().Length > 0)
            {
                new TDynamicSearchHelper(PLocationTable.TableId,
                                         PLocationTable.ColumnLocalityId, CriteriaRow, "Addr1", "Addr1Match", ref CustomWhereCriteria,
                                         ref InternalParameters);
            }

            if (CriteriaRow["Street2"].ToString().Length > 0)
            {
                new TDynamicSearchHelper(PLocationTable.TableId,
                                         PLocationTable.ColumnStreetNameId, CriteriaRow, "Street2", "Street2Match",
                                         ref CustomWhereCriteria,
                                         ref InternalParameters);
            }

            if (CriteriaRow["Addr3"].ToString().Length > 0)
            {
                new TDynamicSearchHelper(PLocationTable.TableId,
                                         PLocationTable.ColumnAddress3Id, CriteriaRow, "Addr3", "Addr3Match", ref CustomWhereCriteria,
                                         ref InternalParameters);
            }

            if (CriteriaRow["City"].ToString().Length > 0)
            {
                new TDynamicSearchHelper(PLocationTable.TableId,
                                         PLocationTable.ColumnCityId, CriteriaRow, "City", "CityMatch", ref CustomWhereCriteria,
                                         ref InternalParameters);
            }

            if (CriteriaRow["PostCode"].ToString().Length > 0)
            {
                new TDynamicSearchHelper(PLocationTable.TableId,
                                         PLocationTable.ColumnPostalCodeId, CriteriaRow, "PostCode", "PostCodeMatch",
                                         ref CustomWhereCriteria,
                                         ref InternalParameters);
            }

            if (CriteriaRow["County"].ToString().Length > 0)
            {
                new TDynamicSearchHelper(PLocationTable.TableId,
                                         PLocationTable.ColumnCountyId, CriteriaRow, "County", "CountyMatch", ref CustomWhereCriteria,
                                         ref InternalParameters);
            }

            if (CriteriaRow["Country"].ToString().Length > 0)
            {
                new TDynamicSearchHelper(PLocationTable.TableId,
                                         PLocationTable.ColumnCountryCodeId, CriteriaRow, "Country", "CountryMatch",
                                         ref CustomWhereCriteria,
                                         ref InternalParameters);
            }

            if (CriteriaRow["LocationKey"].ToString().Length > 0)
            {
                // DISREGARD ALL OTHER SEARCH CRITERIA!!!
                CustomWhereCriteria = "";
                InternalParameters  = new ArrayList();

                CustomWhereCriteria = String.Format("{0} AND PUB.{1}.{2} = ?", CustomWhereCriteria,
                                                    PLocationTable.GetTableDBName(), PLocationTable.GetLocationKeyDBName());

                miParam            = new OdbcParameter("", OdbcType.Decimal, 10);
                miParam.Value      = (object)CriteriaRow["LocationKey"];
                InternalParameters = new ArrayList();
                InternalParameters.Add(miParam);
            }

//           TLogging.LogAtLevel(7, "CustomWhereCriteria: " + CustomWhereCriteria);

            /* Convert ArrayList to a array of ODBCParameters
             * seem to need to declare a type first
             */
            AParametersArray   = ((OdbcParameter[])(InternalParameters.ToArray(typeof(OdbcParameter))));
            InternalParameters = null;             // ensure this is GC'd

            return(CustomWhereCriteria);
        }
Exemple #43
0
        /// <summary>
        /// Returns the PLocationRow of the 'Best Address'.
        /// </summary>
        /// <remarks>The 'DetermineBestAddress' Method overload that returns a <see cref="TLocationPK" /> must
        /// have been run before and that return value must be passed into the present Method with the
        /// <paramref name="ABestLocationPK" /> Argument!!!</remarks>
        /// <param name="ABestLocationPK">Primary Key of the 'Best Location' (as determined by the
        /// 'DetermineBestAddress' Method overload that returns a <see cref="TLocationPK" />).</param>
        /// <param name="ALocationDT">Location Table that contains the Location record that is referenced with
        /// <paramref name="ABestLocationPK" />.</param>
        /// <returns>Location Row of the 'Best Address'.</returns>
        public static PLocationRow FindBestAddressLocation(TLocationPK ABestLocationPK, PLocationTable ALocationDT)
        {
            PLocationRow BestLocationDR;

            if ((ABestLocationPK.SiteKey == -1) &&
                (ABestLocationPK.LocationKey == -1))
            {
                throw new EOPAppException(
                          "FindBestAddressLocation Method was unable to determine the 'Best Address' (PPartnerLocation error)! (Was 'DetermineBestAddress' run before?)");
            }

            BestLocationDR = (PLocationRow)ALocationDT.Rows.Find(
                new object[] { ABestLocationPK.SiteKey, ABestLocationPK.LocationKey });

            if (BestLocationDR == null)
            {
                throw new EOPAppException(
                          "FindBestAddressLocation Method was unable to determine the 'Best Address' (PLocation error)! (Was 'DetermineBestAddress' run before?)");
            }

            return(BestLocationDR);
        }
Exemple #44
0
        public static bool DeletePartner(Int64 APartnerKey, out TVerificationResultCollection AVerificationResult)
        {
            string ShortName;
            TPartnerClass PartnerClass;
            TStdPartnerStatusCode PartnerStatusCode;
            bool ResultValue = false;

            AVerificationResult = null;
            ResultValue = true;

            TDBTransaction Transaction = null;
            bool SubmissionOK = false;

            DBAccess.GDBAccessObj.GetNewOrExistingAutoTransaction(IsolationLevel.Serializable, TEnforceIsolationLevel.eilMinimum,
                ref Transaction, ref SubmissionOK,
                delegate
                {
                    ResultValue =
                        MCommonMain.RetrievePartnerShortName(APartnerKey, out ShortName, out PartnerClass, out PartnerStatusCode, Transaction);

                    /* s_user - delete not allowed by CanPartnerBeDeleted */
                    if (ResultValue)
                    {
                        ResultValue = DeleteEntries(PRecentPartnersTable.GetTableDBName(),
                            PRecentPartnersTable.GetPartnerKeyDBName(),
                            APartnerKey, Transaction);
                    }

                    if (ResultValue)
                    {
                        ResultValue = DeleteEntries(PPartnerGraphicTable.GetTableDBName(),
                            PPartnerGraphicTable.GetPartnerKeyDBName(),
                            APartnerKey, Transaction);
                    }

                    /* Delete extract entries before possibly attempting to delete a  */
                    /* location record referenced in the extract.  Decrease key count */
                    /* in m_extract_master.                                           */
                    if (ResultValue)
                    {
                        // first make sure that extract master tables are up to date
                        // (decrease key count by number of rows to be deleted)
                        MExtractMasterTable ExtractMasterTable;
                        MExtractMasterRow ExtractMasterRow;
                        MExtractTable ExtractTable = MExtractAccess.LoadViaPPartner(APartnerKey, Transaction);

                        foreach (DataRow Row in ExtractTable.Rows)
                        {
                            ExtractMasterTable = MExtractMasterAccess.LoadByPrimaryKey(((MExtractRow)Row).ExtractId, Transaction);
                            ExtractMasterRow = (MExtractMasterRow)ExtractMasterTable.Rows[0];
                            ExtractMasterRow.KeyCount = ExtractMasterRow.KeyCount - 1;
                            MExtractMasterAccess.SubmitChanges(ExtractMasterTable, Transaction);
                        }

                        // now delete the actual extract entries
                        ResultValue = DeleteEntries(MExtractTable.GetTableDBName(),
                            MExtractTable.GetPartnerKeyDBName(),
                            APartnerKey, Transaction);
                    }

                    // Delete Partner Location. If locations were only used by this partner then also delete location record.
                    if (ResultValue)
                    {
                        PPartnerLocationTable PartnerLocationTable = PPartnerLocationAccess.LoadViaPPartner(APartnerKey, Transaction);
                        PPartnerLocationTable OtherPartnerLocationTable;
                        PPartnerLocationRow PartnerLocationRow;
                        PLocationRow LocationRow;
                        PLocationTable LocationTableToDelete = new PLocationTable();

                        foreach (DataRow Row in PartnerLocationTable.Rows)
                        {
                            PartnerLocationRow = (PPartnerLocationRow)Row;
                            OtherPartnerLocationTable = PPartnerLocationAccess.LoadViaPLocation(PartnerLocationRow.SiteKey,
                                PartnerLocationRow.LocationKey,
                                Transaction);

                            // if there is only one partner left using this location (which must be this one) then delete location
                            if ((OtherPartnerLocationTable.Count == 1)
                                && (PartnerLocationRow.LocationKey != 0))
                            {
                                LocationRow = LocationTableToDelete.NewRowTyped();
                                LocationRow.SiteKey = PartnerLocationRow.SiteKey;
                                LocationRow.LocationKey = PartnerLocationRow.LocationKey;
                                LocationTableToDelete.Rows.Add(LocationRow);
                            }
                        }

                        // now first delete the partner locations
                        ResultValue = DeleteEntries(PPartnerLocationTable.GetTableDBName(),
                            PPartnerLocationTable.GetPartnerKeyDBName(),
                            APartnerKey, Transaction);

                        // and now locations if they don't refer to any partners any longer
                        foreach (DataRow RowToDelete in LocationTableToDelete.Rows)
                        {
                            LocationRow = (PLocationRow)RowToDelete;
                            PLocationAccess.DeleteByPrimaryKey(LocationRow.SiteKey, LocationRow.LocationKey, Transaction);
                        }
                    }

                    if (ResultValue)
                    {
                        TSearchCriteria[] PartnerAttributeAccessSC = new TSearchCriteria[] {
                            new TSearchCriteria(PPartnerAttributeTable.GetPartnerKeyDBName(),
                                APartnerKey)
                        };

                        if (PPartnerAttributeAccess.CountUsingTemplate(PartnerAttributeAccessSC, Transaction) > 0)
                        {
                            PPartnerAttributeAccess.DeleteUsingTemplate(PartnerAttributeAccessSC, Transaction);
                        }
                    }

                    if (ResultValue)
                    {
                        ResultValue = ZeroEntries(PChurchTable.GetTableDBName(),
                            PChurchTable.GetContactPartnerKeyDBName(),
                            APartnerKey, Transaction);
                    }

                    if (ResultValue)
                    {
                        ResultValue = ZeroEntries(POrganisationTable.GetTableDBName(),
                            POrganisationTable.GetContactPartnerKeyDBName(),
                            APartnerKey, Transaction);
                    }

                    if (ResultValue)
                    {
                        ResultValue = ZeroEntries(PBankTable.GetTableDBName(),
                            PBankTable.GetContactPartnerKeyDBName(),
                            APartnerKey, Transaction);
                    }

                    if (ResultValue)
                    {
                        ResultValue = ZeroEntries(PVenueTable.GetTableDBName(),
                            PVenueTable.GetContactPartnerKeyDBName(),
                            APartnerKey, Transaction);
                    }

                    // Delete Partner Banking Details.
                    // If Banking Details were only used by this partner then also delete Banking Details record.
                    if (ResultValue)
                    {
                        PPartnerBankingDetailsTable PartnerBankingDetailsTable =
                            PPartnerBankingDetailsAccess.LoadViaPPartner(APartnerKey, Transaction);
                        PPartnerBankingDetailsTable OtherPartnerBankingDetailsTable;
                        PPartnerBankingDetailsRow PartnerBankingDetailsRow;
                        PBankingDetailsRow BankingDetailsRow;
                        PBankingDetailsTable BankingDetailsTableToDelete = new PBankingDetailsTable();

                        foreach (DataRow Row in PartnerBankingDetailsTable.Rows)
                        {
                            PartnerBankingDetailsRow = (PPartnerBankingDetailsRow)Row;
                            OtherPartnerBankingDetailsTable = PPartnerBankingDetailsAccess.LoadViaPBankingDetails(
                                PartnerBankingDetailsRow.BankingDetailsKey,
                                Transaction);

                            // if there is only one partner left using this banking details record (which must be this one) then delete banking details
                            if (OtherPartnerBankingDetailsTable.Count == 1)
                            {
                                BankingDetailsRow = BankingDetailsTableToDelete.NewRowTyped();
                                BankingDetailsRow.BankingDetailsKey = PartnerBankingDetailsRow.BankingDetailsKey;
                                BankingDetailsTableToDelete.Rows.Add(BankingDetailsRow);
                            }
                        }

                        // now first delete the partner banking details
                        ResultValue = DeleteEntries(PPartnerBankingDetailsTable.GetTableDBName(),
                            PPartnerBankingDetailsTable.GetPartnerKeyDBName(),
                            APartnerKey, Transaction);

                        // and now banking details if they don't refer to any partners any longer
                        foreach (DataRow RowToDelete in BankingDetailsTableToDelete.Rows)
                        {
                            BankingDetailsRow = (PBankingDetailsRow)RowToDelete;
                            PBankingDetailsAccess.DeleteByPrimaryKey(BankingDetailsRow.BankingDetailsKey, Transaction);
                        }
                    }

                    if (ResultValue)
                    {
                        ResultValue = DeleteEntries(PPartnerTypeTable.GetTableDBName(),
                            PPartnerTypeTable.GetPartnerKeyDBName(),
                            APartnerKey, Transaction);
                    }

                    if (ResultValue)
                    {
                        ResultValue = DeleteEntries(PPartnerRelationshipTable.GetTableDBName(),
                            PPartnerRelationshipTable.GetPartnerKeyDBName(),
                            APartnerKey, Transaction);
                    }

                    if (ResultValue)
                    {
                        ResultValue = DeleteEntries(PPartnerRelationshipTable.GetTableDBName(),
                            PPartnerRelationshipTable.GetRelationKeyDBName(),
                            APartnerKey, Transaction);
                    }

                    if (ResultValue)
                    {
                        ResultValue = DeleteEntries(PCustomisedGreetingTable.GetTableDBName(),
                            PCustomisedGreetingTable.GetPartnerKeyDBName(),
                            APartnerKey, Transaction);
                    }

                    if (ResultValue)
                    {
                        ResultValue = DeleteEntries(PSubscriptionTable.GetTableDBName(),
                            PSubscriptionTable.GetPartnerKeyDBName(),
                            APartnerKey, Transaction);
                    }

                    // delete reminders before contacts
                    if (ResultValue)
                    {
                        ResultValue = DeleteEntries(PPartnerReminderTable.GetTableDBName(),
                            PPartnerReminderTable.GetPartnerKeyDBName(),
                            APartnerKey, Transaction);
                    }

                    var partnerContacts = MPartner.Partner.WebConnectors.TContactsWebConnector.GetPartnerContactLogData(APartnerKey).PPartnerContact
                                          .AsEnumerable().Select(r =>
                        {
                            var id = r.ItemArray[PPartnerContactTable.ColumnContactLogIdId];
                            return new { ContactLogId = id, deleteThis = !TContactsWebConnector.IsContactLogAssociatedWithMoreThanOnePartner((long)id) };
                        });

                    // Delete contact attributes before deleting contacts
                    if (ResultValue)
                    {
                        String SqlStmt;

                        foreach (var row in partnerContacts)
                        {
                            if (row.deleteThis)
                            {
                                try
                                {
                                    // build sql statement for deletion
                                    SqlStmt = "DELETE FROM " + PPartnerContactAttributeTable.GetTableDBName() +
                                              " WHERE " + PPartnerContactAttributeTable.GetContactIdDBName() +
                                              " IN (SELECT " + PPartnerContactTable.GetContactLogIdDBName() +
                                              " FROM " + PPartnerContactTable.GetTableDBName() +
                                              " WHERE " + PPartnerContactTable.GetPartnerKeyDBName() + " = " + APartnerKey.ToString() +
                                              " AND " + PPartnerContactTable.GetContactLogIdDBName() + " = " + row.ContactLogId + ")";

                                    DBAccess.GDBAccessObj.ExecuteNonQuery(SqlStmt, Transaction);
                                }
                                catch (Exception Exc)
                                {
                                    TLogging.Log(
                                        "An Exception occured during the deletion of " + PPartnerContactAttributeTable.GetTableDBName() +
                                        " while deleting a partner: " + Environment.NewLine + Exc.ToString());

                                    throw;
                                }
                            }
                        }
                    }

                    if (ResultValue)
                    {
                        ResultValue = DeleteEntries(PPartnerContactTable.GetTableDBName(),
                            PPartnerContactTable.GetPartnerKeyDBName(),
                            APartnerKey, Transaction);
                    }

                    // Delete any would-be orphaned ContactLog records
                    if (ResultValue)
                    {
                        foreach (var r in partnerContacts.Where(p => p.deleteThis))
                        {
                            PContactLogAccess.DeleteByPrimaryKey((long)r.ContactLogId, Transaction);
                        }
                    }

                    if (ResultValue)
                    {
                        ResultValue = DeleteEntries(AEmailDestinationTable.GetTableDBName(),
                            AEmailDestinationTable.GetPartnerKeyDBName(),
                            APartnerKey, Transaction);
                    }

                    if (ResultValue)
                    {
                        ResultValue = ZeroEntries(AMotivationDetailTable.GetTableDBName(),
                            AMotivationDetailTable.GetRecipientKeyDBName(),
                            APartnerKey, Transaction);
                    }

                    /* a_recurring_gift - delete not allowed by CanPartnerBeDeleted */
                    /* a_recurring_gift_detail - delete not allowed by CanPartnerBeDeleted */
                    /* a_gift - delete not allowed by CanPartnerBeDeleted */
                    /* a_gift_detail - delete not allowed by CanPartnerBeDeleted */
                    /* a_ap_supplier - delete not allowed by CanPartnerBeDeleted */

                    if (ResultValue)
                    {
                        ResultValue = ZeroEntries(PmDocumentTable.GetTableDBName(),
                            PmDocumentTable.GetContactPartnerKeyDBName(),
                            APartnerKey, Transaction);
                    }

                    if (ResultValue)
                    {
                        ResultValue = DeleteEntries(PDataLabelValuePartnerTable.GetTableDBName(),
                            PDataLabelValuePartnerTable.GetPartnerKeyDBName(),
                            APartnerKey, Transaction);
                    }

                    if (ResultValue)
                    {
                        ResultValue = ZeroEntries(PDataLabelValuePartnerTable.GetTableDBName(),
                            PDataLabelValuePartnerTable.GetValuePartnerKeyDBName(),
                            APartnerKey, Transaction);
                    }

                    if (ResultValue)
                    {
                        ResultValue = ZeroEntries(PDataLabelValueApplicationTable.GetTableDBName(),
                            PDataLabelValueApplicationTable.GetValuePartnerKeyDBName(),
                            APartnerKey, Transaction);
                    }

                    if (ResultValue)
                    {
                        ResultValue = DeleteEntries(PmJobAssignmentTable.GetTableDBName(),
                            PmJobAssignmentTable.GetPartnerKeyDBName(),
                            APartnerKey, Transaction);
                    }

                    if (ResultValue)
                    {
                        ResultValue = DeleteEntries(PTaxTable.GetTableDBName(),
                            PTaxTable.GetPartnerKeyDBName(),
                            APartnerKey, Transaction);
                    }

                    if (ResultValue)
                    {
                        ResultValue = DeleteEntries(PPartnerInterestTable.GetTableDBName(),
                            PPartnerInterestTable.GetPartnerKeyDBName(),
                            APartnerKey, Transaction);
                    }

                    if (ResultValue)
                    {
                        ResultValue = DeleteEntries(PPartnerMergeTable.GetTableDBName(),
                            PPartnerMergeTable.GetMergeFromDBName(),
                            APartnerKey, Transaction);
                    }

                    if (ResultValue)
                    {
                        ResultValue = DeleteEntries(PPartnerMergeTable.GetTableDBName(),
                            PPartnerMergeTable.GetMergeToDBName(),
                            APartnerKey, Transaction);
                    }

                    if (ResultValue)
                    {
                        ResultValue = DeleteEntries(PPartnerGiftDestinationTable.GetTableDBName(),
                            PPartnerGiftDestinationTable.GetPartnerKeyDBName(),
                            APartnerKey, Transaction);
                    }

                    if (ResultValue)
                    {
                        ResultValue = DeleteEntries(PPartnerCommentTable.GetTableDBName(),
                            PPartnerCommentTable.GetPartnerKeyDBName(),
                            APartnerKey, Transaction);
                    }

                    if (ResultValue)
                    {
                        ResultValue = ZeroEntries(PFoundationTable.GetTableDBName(),
                            PFoundationTable.GetContactPartnerDBName(),
                            APartnerKey, Transaction);
                    }

                    if (ResultValue)
                    {
                        ResultValue = ZeroEntries(PFoundationProposalTable.GetTableDBName(),
                            PFoundationProposalTable.GetPartnerSubmittedByDBName(),
                            APartnerKey, Transaction);
                    }

                    // now delete partner class specific information
                    if (ResultValue)
                    {
                        switch (PartnerClass)
                        {
                            case TPartnerClass.FAMILY:
                                ResultValue = DeleteFamily(APartnerKey, Transaction);
                                break;

                            case TPartnerClass.PERSON:
                                ResultValue = DeletePerson(APartnerKey, Transaction);
                                break;

                            case TPartnerClass.UNIT:
                                ResultValue = DeleteUnit(APartnerKey, Transaction);
                                break;

                            case TPartnerClass.ORGANISATION:
                                ResultValue = DeleteOrganisation(APartnerKey, Transaction);
                                break;

                            case TPartnerClass.CHURCH:
                                ResultValue = DeleteChurch(APartnerKey, Transaction);
                                break;

                            case TPartnerClass.BANK:
                                ResultValue = DeleteBank(APartnerKey, Transaction);
                                break;

                            case TPartnerClass.VENUE:
                                ResultValue = DeleteVenue(APartnerKey, Transaction);
                                break;

                            default:
                                break;
                        }
                    }

                    // finally delete p_partner record itself
                    if (ResultValue)
                    {
                        ResultValue = DeleteEntries(PPartnerTable.GetTableDBName(),
                            PPartnerTable.GetPartnerKeyDBName(),
                            APartnerKey, Transaction);

                        SubmissionOK = true;
                    }
                });

            return ResultValue;
        }
        /// <summary>
        /// Loads Partner Location Data from Petra Server into FMainDS.
        /// </summary>
        /// <returns>true if successful, otherwise false.</returns>
        private Boolean LoadDataOnDemand()
        {
            Boolean ReturnValue = true;
            PLocationTable LocationTable = new PLocationTable();

            // Load Partner Locations, if not already loaded
            try
            {
                // initialization only needed when Partner Record already exists
                if (FPetraUtilsObject.ScreenMode != TScreenMode.smNew)
                {
                    // Make sure that Typed DataTables are already there at Client side
                    if (FMainDS.PPartnerLocation == null)
                    {
                        FMainDS.Tables.Add(new PartnerEditTDSPPartnerLocationTable());
                        FMainDS.InitVars();
                    }

                    if (FMainDS.PLocation == null)
                    {
                        FMainDS.Tables.Add(new PLocationTable());
                        FMainDS.InitVars();
                    }

                    if (TClientSettings.DelayedDataLoading)
                    {
                        FMainDS.Merge(FPartnerEditUIConnector.GetDataPartnerLocations(ref LocationTable));
                        FMainDS.Merge(LocationTable);

                        // Make DataRows unchanged
                        if (FMainDS.PPartnerLocation.Rows.Count > 0)
                        {
                            FMainDS.PPartnerLocation.AcceptChanges();
                        }

                        if (FMainDS.PLocation.Rows.Count > 0)
                        {
                            FMainDS.PLocation.AcceptChanges();
                        }
                    }
                }

                if (FMainDS.PPartnerLocation.Rows.Count != 0)
                {
                    ReturnValue = true;
                }
                else
                {
                    ReturnValue = false;
                }
            }
            catch (System.NullReferenceException)
            {
                return false;
            }
            catch (Exception)
            {
                throw;
            }
            return ReturnValue;
        }
Exemple #46
0
        /// <summary>
        /// contructor
        /// </summary>
        /// <param name="ACriteriaData"></param>
        public TPartnerLocationFindUIConnector(DataTable ACriteriaData) : base()
        {
            Hashtable     ColumnNameMapping;
            String        CustomWhereCriteria;
            ArrayList     InternalParameters;
            OdbcParameter miParam;
            DataRow       CriteriaRow;

            FPagedDataSetObject = new TPagedDataSet(new PartnerFindTDSSearchResultTable());
            ColumnNameMapping   = null;

            // get the first and only row
            CriteriaRow = ACriteriaData.Rows[0];

            // used to help with strong typing of columns
            InternalParameters  = new ArrayList();
            CustomWhereCriteria = "";

            if (CriteriaRow["Addr1"].ToString().Length > 0)
            {
                new TDynamicSearchHelper(PLocationTable.TableId,
                                         PLocationTable.ColumnLocalityId, CriteriaRow, "Addr1", "Addr1Match", ref CustomWhereCriteria,
                                         ref InternalParameters);
            }

            if (CriteriaRow["Street2"].ToString().Length > 0)
            {
                new TDynamicSearchHelper(PLocationTable.TableId,
                                         PLocationTable.ColumnStreetNameId, CriteriaRow, "Street2", "Street2Match",
                                         ref CustomWhereCriteria,
                                         ref InternalParameters);
            }

            if (CriteriaRow["Addr3"].ToString().Length > 0)
            {
                new TDynamicSearchHelper(PLocationTable.TableId,
                                         PLocationTable.ColumnAddress3Id, CriteriaRow, "Addr3", "Addr3Match", ref CustomWhereCriteria,
                                         ref InternalParameters);
            }

            if (CriteriaRow["City"].ToString().Length > 0)
            {
                new TDynamicSearchHelper(PLocationTable.TableId,
                                         PLocationTable.ColumnCityId, CriteriaRow, "City", "CityMatch", ref CustomWhereCriteria,
                                         ref InternalParameters);
            }

            if (CriteriaRow["PostCode"].ToString().Length > 0)
            {
                new TDynamicSearchHelper(PLocationTable.TableId,
                                         PLocationTable.ColumnPostalCodeId, CriteriaRow, "PostCode", "PostCodeMatch",
                                         ref CustomWhereCriteria,
                                         ref InternalParameters);
            }

            if (CriteriaRow["County"].ToString().Length > 0)
            {
                new TDynamicSearchHelper(PLocationTable.TableId,
                                         PLocationTable.ColumnCountyId, CriteriaRow, "County", "CountyMatch", ref CustomWhereCriteria,
                                         ref InternalParameters);
            }

            if (CriteriaRow["Country"].ToString().Length > 0)
            {
                new TDynamicSearchHelper(PLocationTable.TableId,
                                         PLocationTable.ColumnCountryCodeId, CriteriaRow, "Country", "CountryMatch",
                                         ref CustomWhereCriteria,
                                         ref InternalParameters);
            }

            if (CriteriaRow["LocationKey"].ToString().Length > 0)
            {
                // DISREGARD ALL OTHER SEARCH CRITERIA!!!
                CustomWhereCriteria = "";
                InternalParameters  = new ArrayList();

                CustomWhereCriteria = String.Format("{0} AND PUB.{1}.{2} = ?", CustomWhereCriteria,
                                                    PLocationTable.GetTableDBName(), PLocationTable.GetLocationKeyDBName());

                miParam            = new OdbcParameter("", OdbcType.Decimal, 10);
                miParam.Value      = (object)CriteriaRow["LocationKey"];
                InternalParameters = new ArrayList();
                InternalParameters.Add(miParam);
            }

            Console.WriteLine("WHERE CLAUSE: " + CustomWhereCriteria);
            FPagedDataSetObject.FindParameters = new TPagedDataSet.TAsyncFindParameters(
                " p_city_c, p_postal_code_c,  p_locality_c, p_street_name_c, p_address_3_c, p_county_c, p_country_code_c, p_location_key_i, p_site_key_n ",
                "PUB_p_location ",
                " p_location_key_i<>-1 " + CustomWhereCriteria + ' ',
                "p_city_c ",
                ColumnNameMapping,
                ((OdbcParameter[])(InternalParameters.ToArray(typeof(OdbcParameter)))));

            // fields
            // table
            // where
            // order by
            // both empty for now

            string session = TSession.GetSessionID();

            //
            // Start the Find Thread
            //
            try
            {
                ThreadStart myThreadStart = delegate {
                    FPagedDataSetObject.ExecuteQuery(session);
                };
                FFindThread      = new Thread(myThreadStart);
                FFindThread.Name = "PartnerLocationFind" + Guid.NewGuid().ToString();
                FFindThread.Start();
            }
            catch (Exception)
            {
                throw;
            }
        }
Exemple #47
0
        public static bool CreateNewLedger(Int32 ANewLedgerNumber,
            String ALedgerName,
            String ACountryCode,
            String ABaseCurrency,
            String AIntlCurrency,
            DateTime ACalendarStartDate,
            Int32 ANumberOfPeriods,
            Int32 ACurrentPeriod,
            Int32 ANumberOfFwdPostingPeriods,
            bool IchIsAsset,
            bool AActivateGiftProcessing,
            Int32 AStartingReceiptNumber,
            bool AActivateAccountsPayable,
            out TVerificationResultCollection AVerificationResult)
        {
            AVerificationResult = null;
            bool AllOK = false;

            TDBTransaction Transaction = DBAccess.GDBAccessObj.BeginTransaction(IsolationLevel.Serializable);

            try
            {
                // check if such a ledger already exists
                ALedgerTable tempLedger = ALedgerAccess.LoadByPrimaryKey(ANewLedgerNumber, Transaction);

                if (tempLedger.Count > 0)
                {
                    AVerificationResult = new TVerificationResultCollection();
                    string msg = String.Format(Catalog.GetString(
                            "There is already a ledger with number {0}. Please choose another number."), ANewLedgerNumber);
                    AVerificationResult.Add(new TVerificationResult(Catalog.GetString("Creating Ledger"), msg, TResultSeverity.Resv_Critical));

                    return false;
                }

                if ((ANewLedgerNumber <= 1) || (ANewLedgerNumber > 9999))
                {
                    // ledger number 1 does not work, because the root unit has partner key 1000000.
                    AVerificationResult = new TVerificationResultCollection();
                    string msg = String.Format(Catalog.GetString(
                            "Invalid number {0} for a ledger. Please choose a number between 2 and 9999."), ANewLedgerNumber);
                    AVerificationResult.Add(new TVerificationResult(Catalog.GetString("Creating Ledger"), msg, TResultSeverity.Resv_Critical));

                    return false;
                }

                Int64 PartnerKey = Convert.ToInt64(ANewLedgerNumber) * 1000000L;
                GLSetupTDS MainDS = new GLSetupTDS();

                ALedgerRow ledgerRow = MainDS.ALedger.NewRowTyped();
                ledgerRow.LedgerNumber = ANewLedgerNumber;
                ledgerRow.LedgerName = ALedgerName;
                ledgerRow.CurrentPeriod = ACurrentPeriod;
                ledgerRow.NumberOfAccountingPeriods = ANumberOfPeriods;
                ledgerRow.NumberFwdPostingPeriods = ANumberOfFwdPostingPeriods;
                ledgerRow.BaseCurrency = ABaseCurrency;
                ledgerRow.IntlCurrency = AIntlCurrency;
                ledgerRow.ActualsDataRetention = 11;
                ledgerRow.GiftDataRetention = 11;
                ledgerRow.BudgetDataRetention = 2;
                ledgerRow.CountryCode = ACountryCode;
                ledgerRow.ForexGainsLossesAccount = "5003";
                ledgerRow.PartnerKey = PartnerKey;

                if (ANumberOfPeriods == 12)
                {
                    ledgerRow.CalendarMode = true;
                }
                else
                {
                    ledgerRow.CalendarMode = false;
                }

                MainDS.ALedger.Rows.Add(ledgerRow);

                PPartnerRow partnerRow;

                if (!PPartnerAccess.Exists(PartnerKey, Transaction))
                {
                    partnerRow = MainDS.PPartner.NewRowTyped();
                    ledgerRow.PartnerKey = PartnerKey;
                    partnerRow.PartnerKey = PartnerKey;
                    partnerRow.PartnerShortName = ALedgerName;
                    partnerRow.StatusCode = MPartnerConstants.PARTNERSTATUS_ACTIVE;
                    partnerRow.PartnerClass = MPartnerConstants.PARTNERCLASS_UNIT;
                    MainDS.PPartner.Rows.Add(partnerRow);

                    // create or use addresses (only if partner record is created here as
                    // otherwise we assume that Partner has address already)
                    PLocationRow locationRow;
                    PLocationTable LocTemplateTable;
                    PLocationTable LocResultTable;
                    PLocationRow LocTemplateRow;
                    StringCollection LocTemplateOperators;

                    // find address with country set
                    LocTemplateTable = new PLocationTable();
                    LocTemplateRow = LocTemplateTable.NewRowTyped(false);
                    LocTemplateRow.SiteKey = 0;
                    LocTemplateRow.StreetName = Catalog.GetString("No valid address on file");
                    LocTemplateRow.CountryCode = ACountryCode;
                    LocTemplateOperators = new StringCollection();

                    LocResultTable = PLocationAccess.LoadUsingTemplate(LocTemplateRow, LocTemplateOperators, Transaction);

                    if (LocResultTable.Count > 0)
                    {
                        locationRow = (PLocationRow)LocResultTable.Rows[0];
                    }
                    else
                    {
                        // no location record exists yet: create new one
                        locationRow = MainDS.PLocation.NewRowTyped();
                        locationRow.SiteKey = 0;
                        locationRow.LocationKey = (int)DBAccess.GDBAccessObj.GetNextSequenceValue(
                            TSequenceNames.seq_location_number.ToString(), Transaction);
                        locationRow.StreetName = Catalog.GetString("No valid address on file");
                        locationRow.CountryCode = ACountryCode;
                        MainDS.PLocation.Rows.Add(locationRow);
                    }

                    // now create partner location record
                    PPartnerLocationRow partnerLocationRow = MainDS.PPartnerLocation.NewRowTyped();
                    partnerLocationRow.SiteKey = locationRow.SiteKey;
                    partnerLocationRow.PartnerKey = PartnerKey;
                    partnerLocationRow.LocationKey = locationRow.LocationKey;
                    partnerLocationRow.DateEffective = DateTime.Today;
                    MainDS.PPartnerLocation.Rows.Add(partnerLocationRow);
                }
                else
                {
                    // partner record already exists in database -> update ledger name
                    PPartnerAccess.LoadByPrimaryKey(MainDS, PartnerKey, Transaction);
                    partnerRow = (PPartnerRow)MainDS.PPartner.Rows[0];
                    partnerRow.PartnerShortName = ALedgerName;
                }

                PPartnerTypeAccess.LoadViaPPartner(MainDS, PartnerKey, Transaction);
                PPartnerTypeRow partnerTypeRow;

                // only create special type "LEDGER" if it does not exist yet
                if (MainDS.PPartnerType.Rows.Find(new object[] { PartnerKey, MPartnerConstants.PARTNERTYPE_LEDGER }) == null)
                {
                    partnerTypeRow = MainDS.PPartnerType.NewRowTyped();
                    partnerTypeRow.PartnerKey = PartnerKey;
                    partnerTypeRow.TypeCode = MPartnerConstants.PARTNERTYPE_LEDGER;
                    MainDS.PPartnerType.Rows.Add(partnerTypeRow);
                }

                if (!PUnitAccess.Exists(PartnerKey, Transaction))
                {
                    PUnitRow unitRow = MainDS.PUnit.NewRowTyped();
                    unitRow.PartnerKey = PartnerKey;
                    unitRow.UnitName = ALedgerName;
                    MainDS.PUnit.Rows.Add(unitRow);
                }

                String ModuleId = "LEDGER" + ANewLedgerNumber.ToString("0000");

                if (!SModuleAccess.Exists(ModuleId, Transaction))
                {
                    SModuleRow moduleRow = MainDS.SModule.NewRowTyped();
                    moduleRow.ModuleId = ModuleId;
                    moduleRow.ModuleName = moduleRow.ModuleId;
                    MainDS.SModule.Rows.Add(moduleRow);
                }

                // if this is the first ledger, make it the default site
                SSystemDefaultsTable systemDefaults = SSystemDefaultsAccess.LoadByPrimaryKey("SiteKey", Transaction);

                if (systemDefaults.Rows.Count == 0)
                {
                    SSystemDefaultsRow systemDefaultsRow = MainDS.SSystemDefaults.NewRowTyped();
                    systemDefaultsRow.DefaultCode = SharedConstants.SYSDEFAULT_SITEKEY;
                    systemDefaultsRow.DefaultDescription = "there has to be one site key for the database";
                    systemDefaultsRow.DefaultValue = PartnerKey.ToString("0000000000");
                    MainDS.SSystemDefaults.Rows.Add(systemDefaultsRow);
                }

                //TODO: Calendar vs Financial Date Handling - Need to review this
                // create calendar
                // at the moment we only support financial years that start on the first day of a month
                // and currently only 12 or 13 periods are allowed and a maximum of 8 forward periods
                DateTime periodStartDate = ACalendarStartDate;

                for (Int32 periodNumber = 1; periodNumber <= ANumberOfPeriods + ANumberOfFwdPostingPeriods; periodNumber++)
                {
                    AAccountingPeriodRow accountingPeriodRow = MainDS.AAccountingPeriod.NewRowTyped();
                    accountingPeriodRow.LedgerNumber = ANewLedgerNumber;
                    accountingPeriodRow.AccountingPeriodNumber = periodNumber;
                    accountingPeriodRow.PeriodStartDate = periodStartDate;

                    if ((ANumberOfPeriods == 13)
                        && (periodNumber == 12))
                    {
                        // in case of 12 periods the second last period represents the last month except for the very last day
                        accountingPeriodRow.PeriodEndDate = periodStartDate.AddMonths(1).AddDays(-2);
                    }
                    else if ((ANumberOfPeriods == 13)
                             && (periodNumber == 13))
                    {
                        // in case of 13 periods the last period just represents the very last day of the financial year
                        accountingPeriodRow.PeriodEndDate = periodStartDate;
                    }
                    else
                    {
                        accountingPeriodRow.PeriodEndDate = periodStartDate.AddMonths(1).AddDays(-1);
                    }

                    accountingPeriodRow.AccountingPeriodDesc = periodStartDate.ToString("MMMM");
                    MainDS.AAccountingPeriod.Rows.Add(accountingPeriodRow);
                    periodStartDate = accountingPeriodRow.PeriodEndDate.AddDays(1);
                }

                // mark cached table for accounting periods to be refreshed
                TCacheableTablesManager.GCacheableTablesManager.MarkCachedTableNeedsRefreshing(
                    TCacheableFinanceTablesEnum.AccountingPeriodList.ToString());

                AAccountingSystemParameterRow accountingSystemParameterRow = MainDS.AAccountingSystemParameter.NewRowTyped();
                accountingSystemParameterRow.LedgerNumber = ANewLedgerNumber;
                accountingSystemParameterRow.ActualsDataRetention = ledgerRow.ActualsDataRetention;
                accountingSystemParameterRow.GiftDataRetention = ledgerRow.GiftDataRetention;
                accountingSystemParameterRow.NumberFwdPostingPeriods = ledgerRow.NumberFwdPostingPeriods;
                accountingSystemParameterRow.NumberOfAccountingPeriods = ledgerRow.NumberOfAccountingPeriods;
                accountingSystemParameterRow.BudgetDataRetention = ledgerRow.BudgetDataRetention;
                MainDS.AAccountingSystemParameter.Rows.Add(accountingSystemParameterRow);

                // activate GL subsystem (this is always active)
                ASystemInterfaceRow systemInterfaceRow = MainDS.ASystemInterface.NewRowTyped();
                systemInterfaceRow.LedgerNumber = ANewLedgerNumber;

                systemInterfaceRow.SubSystemCode = CommonAccountingSubSystemsEnum.GL.ToString();
                systemInterfaceRow.SetUpComplete = true;
                MainDS.ASystemInterface.Rows.Add(systemInterfaceRow);


                ATransactionTypeRow transactionTypeRow;

                // TODO: this might be different for other account or costcentre names
                transactionTypeRow = MainDS.ATransactionType.NewRowTyped();
                transactionTypeRow.LedgerNumber = ANewLedgerNumber;
                transactionTypeRow.SubSystemCode = CommonAccountingSubSystemsEnum.GL.ToString();
                transactionTypeRow.TransactionTypeCode = CommonAccountingTransactionTypesEnum.ALLOC.ToString();
                transactionTypeRow.DebitAccountCode = "BAL SHT";
                transactionTypeRow.CreditAccountCode = "BAL SHT";
                transactionTypeRow.TransactionTypeDescription = "Allocation Journal";
                transactionTypeRow.SpecialTransactionType = true;
                MainDS.ATransactionType.Rows.Add(transactionTypeRow);

                transactionTypeRow = MainDS.ATransactionType.NewRowTyped();
                transactionTypeRow.LedgerNumber = ANewLedgerNumber;
                transactionTypeRow.SubSystemCode = CommonAccountingSubSystemsEnum.GL.ToString();
                transactionTypeRow.TransactionTypeCode = CommonAccountingTransactionTypesEnum.REALLOC.ToString();
                transactionTypeRow.DebitAccountCode = "BAL SHT";
                transactionTypeRow.CreditAccountCode = "BAL SHT";
                transactionTypeRow.TransactionTypeDescription = "Reallocation Journal";
                transactionTypeRow.SpecialTransactionType = true;
                MainDS.ATransactionType.Rows.Add(transactionTypeRow);

                transactionTypeRow = MainDS.ATransactionType.NewRowTyped();
                transactionTypeRow.LedgerNumber = ANewLedgerNumber;
                transactionTypeRow.SubSystemCode = CommonAccountingSubSystemsEnum.GL.ToString();
                transactionTypeRow.TransactionTypeCode = CommonAccountingTransactionTypesEnum.REVAL.ToString();
                transactionTypeRow.DebitAccountCode = "5003";
                transactionTypeRow.CreditAccountCode = "5003";
                transactionTypeRow.TransactionTypeDescription = "Foreign Exchange Revaluation";
                transactionTypeRow.SpecialTransactionType = true;
                MainDS.ATransactionType.Rows.Add(transactionTypeRow);

                transactionTypeRow = MainDS.ATransactionType.NewRowTyped();
                transactionTypeRow.LedgerNumber = ANewLedgerNumber;
                transactionTypeRow.SubSystemCode = CommonAccountingSubSystemsEnum.GL.ToString();
                transactionTypeRow.TransactionTypeCode = CommonAccountingTransactionTypesEnum.STD.ToString();
                transactionTypeRow.DebitAccountCode = MFinanceConstants.ACCOUNT_BAL_SHT;
                transactionTypeRow.CreditAccountCode = MFinanceConstants.ACCOUNT_BAL_SHT;
                transactionTypeRow.TransactionTypeDescription = "Standard Journal";
                transactionTypeRow.SpecialTransactionType = false;
                MainDS.ATransactionType.Rows.Add(transactionTypeRow);


                AValidLedgerNumberTable validLedgerNumberTable = AValidLedgerNumberAccess.LoadByPrimaryKey(ANewLedgerNumber, PartnerKey, Transaction);

                if (validLedgerNumberTable.Rows.Count == 0)
                {
                    AValidLedgerNumberRow validLedgerNumberRow = MainDS.AValidLedgerNumber.NewRowTyped();
                    validLedgerNumberRow.PartnerKey = PartnerKey;
                    validLedgerNumberRow.LedgerNumber = ANewLedgerNumber;

                    // TODO can we assume that ledger 4 is used for international clearing?
                    // but in the empty database, that ledger and therefore p_partner with key 4000000 does not exist
                    // validLedgerNumberRow.IltProcessingCentre = 4000000;

                    validLedgerNumberRow.CostCentreCode = (ANewLedgerNumber * 100).ToString("0000");
                    MainDS.AValidLedgerNumber.Rows.Add(validLedgerNumberRow);
                }

                ACostCentreTypesRow costCentreTypesRow = MainDS.ACostCentreTypes.NewRowTyped();
                costCentreTypesRow.LedgerNumber = ANewLedgerNumber;
                costCentreTypesRow.CostCentreType = "Local";
                costCentreTypesRow.Deletable = false;
                MainDS.ACostCentreTypes.Rows.Add(costCentreTypesRow);
                costCentreTypesRow = MainDS.ACostCentreTypes.NewRowTyped();
                costCentreTypesRow.LedgerNumber = ANewLedgerNumber;
                costCentreTypesRow.CostCentreType = "Foreign";
                costCentreTypesRow.Deletable = false;
                MainDS.ACostCentreTypes.Rows.Add(costCentreTypesRow);

                ImportDefaultAccountHierarchy(ref MainDS, ANewLedgerNumber, ref AVerificationResult);
                ImportDefaultCostCentreHierarchy(ref MainDS, ANewLedgerNumber, ALedgerName);
                ImportDefaultMotivations(ref MainDS, ANewLedgerNumber);
                ImportDefaultAdminGrantsPayableReceivable(ref MainDS, ANewLedgerNumber);

                // TODO: modify UI navigation yml file etc?
                // TODO: permissions for which users?

                GLSetupTDSAccess.SubmitChanges(MainDS);

                // activate gift processing subsystem
                if (AActivateGiftProcessing)
                {
                    ActivateGiftProcessingSubsystem(ANewLedgerNumber, AStartingReceiptNumber);
                }

                // activate accounts payable subsystem
                if (AActivateAccountsPayable)
                {
                    ActivateAccountsPayableSubsystem(ANewLedgerNumber);
                }

                // give the current user access permissions to this new ledger
                SUserModuleAccessPermissionTable moduleAccessPermissionTable = new SUserModuleAccessPermissionTable();

                SUserModuleAccessPermissionRow moduleAccessPermissionRow = moduleAccessPermissionTable.NewRowTyped();
                moduleAccessPermissionRow.UserId = UserInfo.GUserInfo.UserID;
                moduleAccessPermissionRow.ModuleId = "LEDGER" + ANewLedgerNumber.ToString("0000");
                moduleAccessPermissionRow.CanAccess = true;
                moduleAccessPermissionTable.Rows.Add(moduleAccessPermissionRow);


                SUserModuleAccessPermissionAccess.SubmitChanges(moduleAccessPermissionTable, Transaction);

                // create system analysis types for the new ledger
                AAnalysisTypeAccess.LoadAll(MainDS, Transaction);
                AAnalysisTypeTable NewAnalysisTypes = new AAnalysisTypeTable();

                foreach (AAnalysisTypeRow AnalysisTypeRow in MainDS.AAnalysisType.Rows)
                {
                    if (AnalysisTypeRow.SystemAnalysisType
                        && !NewAnalysisTypes.Rows.Contains(new Object[] { ANewLedgerNumber, AnalysisTypeRow.AnalysisTypeCode }))
                    {
                        AAnalysisTypeRow NewAnalysisType = NewAnalysisTypes.NewRowTyped();
                        NewAnalysisType.ItemArray = (object[])AnalysisTypeRow.ItemArray.Clone();
                        NewAnalysisType.LedgerNumber = ANewLedgerNumber;
                        NewAnalysisTypes.Rows.Add(NewAnalysisType);
                    }
                }

                AAnalysisTypeAccess.SubmitChanges(NewAnalysisTypes, Transaction);


                AllOK = true;
            }
            catch (Exception Exc)
            {
                TLogging.Log("An Exception occured during the creation of a new Ledger:" + Environment.NewLine + Exc.ToString());

                DBAccess.GDBAccessObj.RollbackTransaction();

                throw;
            }
            finally
            {
                if (AllOK)
                {
                    DBAccess.GDBAccessObj.CommitTransaction();

                    //
                    // If the user has specified that ICH is an asset,
                    // I need to re-write it into the hierarchy:
                    if (IchIsAsset)
                    {
                        RewireIchIsAsset(ANewLedgerNumber);
                    }
                }
                else
                {
                    DBAccess.GDBAccessObj.RollbackTransaction();
                }
            }

            return AllOK;
        }
        public static DataTable GetEventUnits()
        {
            List <OdbcParameter> SqlParameterList = new List <OdbcParameter>();

            DataColumn[] Key    = new DataColumn[3];
            DataTable    Events = new DataTable();

            if (TLogging.DL >= 9)
            {
                Console.WriteLine("GetEventUnits called!");
            }

            TDBTransaction Transaction = null;

            DBAccess.GDBAccessObj.BeginAutoReadTransaction(IsolationLevel.ReadCommitted,
                                                           ref Transaction,
                                                           delegate
            {
                string SqlStmt =
                    "SELECT DISTINCT " +
                    PPartnerTable.GetPartnerShortNameDBName() +
                    ", " + PPartnerTable.GetPartnerClassDBName() +
                    ", " + PUnitTable.GetOutreachCodeDBName() +
                    ", " + PCountryTable.GetTableDBName() + "." + PCountryTable.GetCountryNameDBName() +
                    ", " + PPartnerLocationTable.GetTableDBName() + "." + PPartnerLocationTable.GetSiteKeyDBName() +
                    ", " + PPartnerLocationTable.GetTableDBName() + "." + PPartnerLocationTable.GetLocationKeyDBName() +
                    ", " + PPartnerLocationTable.GetTableDBName() + "." + PPartnerLocationTable.GetDateEffectiveDBName() +
                    ", " + PPartnerLocationTable.GetTableDBName() + "." + PPartnerLocationTable.GetDateGoodUntilDBName() +

                    ", " + PPartnerTable.GetTableDBName() + "." + PPartnerTable.GetPartnerKeyDBName() +
                    ", " + PUnitTable.GetUnitTypeCodeDBName() +
                    ", " + PUnitTable.GetUnitNameDBName() +

                    " FROM pub_" + PPartnerTable.GetTableDBName() +
                    ", pub_" + PUnitTable.GetTableDBName() +
                    ", pub_" + PLocationTable.GetTableDBName() +
                    ", pub_" + PPartnerLocationTable.GetTableDBName() +
                    ", pub_" + PCountryTable.GetTableDBName() +

                    " WHERE " +
                    PPartnerTable.GetTableDBName() + "." + PPartnerTable.GetPartnerKeyDBName() + " = " +
                    PUnitTable.GetTableDBName() + "." + PUnitTable.GetPartnerKeyDBName() + " AND " +

                    PPartnerTable.GetTableDBName() + "." + PPartnerTable.GetPartnerKeyDBName() + " = " +
                    PPartnerLocationTable.GetTableDBName() + "." + PPartnerLocationTable.GetPartnerKeyDBName() + " AND " +
                    PLocationTable.GetTableDBName() + "." + PLocationTable.GetSiteKeyDBName() + " = " +
                    PPartnerLocationTable.GetTableDBName() + "." + PPartnerLocationTable.GetSiteKeyDBName() + " AND " +
                    PLocationTable.GetTableDBName() + "." + PLocationTable.GetLocationKeyDBName() + " = " +
                    PPartnerLocationTable.GetTableDBName() + "." + PPartnerLocationTable.GetLocationKeyDBName() + " AND " +
                    PCountryTable.GetTableDBName() + "." + PCountryTable.GetCountryCodeDBName() + " = " +
                    PLocationTable.GetTableDBName() + "." + PLocationTable.GetCountryCodeDBName() + " AND " +

                    PPartnerTable.GetStatusCodeDBName() + " = 'ACTIVE' " + " AND " +
                    PPartnerTable.GetPartnerClassDBName() + " = 'UNIT' ";

                // sort rows according to name
                SqlStmt = SqlStmt + " ORDER BY " + PPartnerTable.GetPartnerShortNameDBName();

                Events = DBAccess.GDBAccessObj.SelectDT(SqlStmt, "events",
                                                        Transaction, SqlParameterList.ToArray());

                Key[0]            = Events.Columns[PPartnerTable.GetPartnerKeyDBName()];
                Key[1]            = Events.Columns[PPartnerLocationTable.GetSiteKeyDBName()];
                Key[2]            = Events.Columns[PPartnerLocationTable.GetLocationKeyDBName()];
                Events.PrimaryKey = Key;
            });

            return(Events);
        }
        /// <summary>
        /// Determines which address is the 'Best Address' of a Partner, and marks it in the DataColumn 'BestAddress'.
        /// </summary>
        /// <remarks>There are convenient overloaded server-side Methods, Ict.Petra.Server.MPartner.ServerCalculations.DetermineBestAddress,
        /// which work by specifying the PartnerKey of a Partner in an Argument.</remarks>
        /// <param name="APartnerLocationsDT">DataTable containing the addresses of a Partner.</param>
        /// <returns>A <see cref="TLocationPK" /> which points to the 'Best Address'. If no 'Best Address' was found,
        /// SiteKey and LocationKey of this instance will be both -1.</returns>
        public static TLocationPK DetermineBestAddress(DataTable APartnerLocationsDT)
        {
            TLocationPK ReturnValue;

            DataRow[]    OrderedRows;
            System.Int32 CurrentRow;
            System.Int32 BestRow;
            System.Int16 FirstRowAddrOrder;
            bool         FirstRowMailingAddress;

            System.DateTime BestRowDate;
            System.DateTime TempDate;
            CurrentRow = 0;
            BestRow    = 0;
            bool Unchanged = false;

            TLogging.LogAtLevel(8, "Calculations.DetermineBestAddress: processing " + APartnerLocationsDT.Rows.Count.ToString() + " rows...");

            if (APartnerLocationsDT == null)
            {
                throw new ArgumentException("Argument APartnerLocationsDT must not be null");
            }

            if (!APartnerLocationsDT.Columns.Contains(PARTNERLOCATION_BESTADDR_COLUMN))
            {
                DeterminePartnerLocationsDateStatus(APartnerLocationsDT, DateTime.Today);
            }

            /*
             *  Add custom DataColumn if its not part of the DataTable yet
             */
            if (!APartnerLocationsDT.Columns.Contains(PARTNERLOCATION_BESTADDR_COLUMN))
            {
                APartnerLocationsDT.Columns.Add(new System.Data.DataColumn(PARTNERLOCATION_BESTADDR_COLUMN, typeof(Boolean)));
            }

            /*
             * Order tables' rows: first all records with p_send_mail_l = true, these are ordered
             * ascending by Icon, then all records with p_send_mail_l = false, these are ordered
             * ascending by Icon.
             */
            OrderedRows = APartnerLocationsDT.Select(APartnerLocationsDT.DefaultView.RowFilter,
                                                     PPartnerLocationTable.GetSendMailDBName() + " DESC, " + PartnerEditTDSPPartnerLocationTable.GetIconDBName() + " ASC",
                                                     DataViewRowState.CurrentRows);

            if (OrderedRows.Length > 1)
            {
                FirstRowAddrOrder      = Convert.ToInt16(OrderedRows[0][PartnerEditTDSPPartnerLocationTable.GetIconDBName()]);
                FirstRowMailingAddress = Convert.ToBoolean(OrderedRows[0][PPartnerLocationTable.GetSendMailDBName()]);

                // determine pBestRowDate
                if (FirstRowAddrOrder != 3)
                {
                    BestRowDate = TSaveConvert.ObjectToDate(OrderedRows[CurrentRow][PPartnerLocationTable.GetDateEffectiveDBName()]);
                }
                else
                {
                    BestRowDate = TSaveConvert.ObjectToDate(OrderedRows[CurrentRow][PPartnerLocationTable.GetDateGoodUntilDBName()]);
                }

                // iterate through the sorted rows
                for (CurrentRow = 0; CurrentRow <= OrderedRows.Length - 1; CurrentRow += 1)
                {
                    Unchanged = OrderedRows[CurrentRow].RowState == DataRowState.Unchanged;

                    // reset any row that might have been marked as 'best' before
                    OrderedRows[CurrentRow][PartnerEditTDSPPartnerLocationTable.GetBestAddressDBName()] = ((object)0);

                    // We do not want changing the BestAddress column to enable save. So revert row status to original.
                    if (Unchanged)
                    {
                        OrderedRows[CurrentRow].AcceptChanges();
                    }

                    // determine pTempDate
                    if (FirstRowAddrOrder != 3)
                    {
                        TempDate = TSaveConvert.ObjectToDate(OrderedRows[CurrentRow][PPartnerLocationTable.GetDateEffectiveDBName()]);
                    }
                    else
                    {
                        TempDate = TSaveConvert.ObjectToDate(OrderedRows[CurrentRow][PPartnerLocationTable.GetDateGoodUntilDBName()]);
                    }

                    // still the same ADDR_ORDER than the ADDR_ORDER of the first row and
                    // still the same Mailing Address than the Mailing Address flag of the first row > proceed
                    if ((Convert.ToInt16(OrderedRows[CurrentRow][PartnerEditTDSPPartnerLocationTable.GetIconDBName()]) == FirstRowAddrOrder) &&
                        (Convert.ToBoolean(OrderedRows[CurrentRow][PPartnerLocationTable.GetSendMailDBName()]) == FirstRowMailingAddress))
                    {
                        switch (FirstRowAddrOrder)
                        {
                        case 1:
                        case 3:

                            // find the Row with the highest p_date_effective_d (or p_date_good_until_d) date
                            if (TempDate > BestRowDate)
                            {
                                BestRowDate = TempDate;
                                BestRow     = CurrentRow;
                            }

                            break;

                        case 2:

                            // find the Row with the lowest p_date_effective_d date
                            if (TempDate < BestRowDate)
                            {
                                BestRowDate = TempDate;
                                BestRow     = CurrentRow;
                            }

                            break;
                        }
                    }
                }

                Unchanged = OrderedRows[0].RowState == DataRowState.Unchanged;

                // mark the location that was determined to be the 'best'
                OrderedRows[BestRow][PartnerEditTDSPPartnerLocationTable.GetBestAddressDBName()] = ((object)1);

                // We do not want changing the BestAddress column to enable save. So revert row status to original.
                if (Unchanged)
                {
                    OrderedRows[0].AcceptChanges();
                }

                ReturnValue =
                    new TLocationPK(Convert.ToInt64(OrderedRows[BestRow][PLocationTable.GetSiteKeyDBName()]),
                                    Convert.ToInt32(OrderedRows[BestRow][PLocationTable.GetLocationKeyDBName()]));
            }
            else
            {
                if (OrderedRows.Length == 1)
                {
                    Unchanged = OrderedRows[0].RowState == DataRowState.Unchanged;

                    // mark the only location to be the 'best'
                    OrderedRows[0][PartnerEditTDSPPartnerLocationTable.GetBestAddressDBName()] = ((object)1);

                    // We do not want changing the BestAddress column to enable save. So revert row status to original.
                    if (Unchanged)
                    {
                        OrderedRows[0].AcceptChanges();
                    }

                    ReturnValue = new TLocationPK(Convert.ToInt64(OrderedRows[0][PLocationTable.GetSiteKeyDBName()]),
                                                  Convert.ToInt32(OrderedRows[0][PLocationTable.GetLocationKeyDBName()]));
                }
                else
                {
                    ReturnValue = new TLocationPK();
                }
            }

            return(ReturnValue);
        }
Exemple #50
0
        /// <summary>
        /// Retrieves all of the PartnerInfo data.
        /// </summary>
        /// <param name="APartnerKey">PartnerKey of Partner to find the PartnerInfo data for</param>
        /// <param name="APartnerInfoDS">Typed DataSet that contains the requested data.</param>
        /// <param name="AReadTransaction" >Open DB Transaction.</param>
        /// <returns>True if Partner exists, otherwise false.</returns>
        public static bool AllPartnerInfoData(Int64 APartnerKey, ref PartnerInfoTDS APartnerInfoDS,
                                              TDBTransaction AReadTransaction)
        {
            bool        ReturnValue = false;
            PPartnerRow PartnerDR;

            TLocationPK           BestLocationPK;
            PLocationRow          LocationDR;
            PLocationRow          LocationDR2;
            PPartnerLocationRow   PartnerLocationDR;
            PPartnerLocationRow   PartnerLocationDR2;
            PLocationTable        LocationDT;
            PPartnerLocationTable PartnerLocationDT;

            try
            {
                /*
                 * Check for existance of Partner
                 */
                PartnerDR = MCommonMain.CheckPartnerExists2(APartnerKey, true, AReadTransaction.DataBaseObj);

                if (PartnerDR != null)
                {
                    /*
                     * Perform security checks; these throw ESecurityPartnerAccessDeniedException
                     * in case access isn't granted.
                     */
                    TSecurity.CanAccessPartnerExc(PartnerDR, AReadTransaction.DataBaseObj);

                    /*
                     * Get the Partner's Address data of its 'Best' Address
                     */
                    if (TMailing.GetPartnersBestLocationData(APartnerKey, out BestLocationPK,
                                                             out LocationDR, out PartnerLocationDR, AReadTransaction.DataBaseObj))
                    {
                        #region Process Address

                        /*
                         * Check for existance of PLocation and PPartnerLocation Tables in the passed in
                         * DataSet APartnerInfoDS.
                         */
                        if (!APartnerInfoDS.Tables.Contains(PLocationTable.GetTableName()))
                        {
                            // Need to create Table here
                            APartnerInfoDS.Tables.Add(new PLocationTable());
                        }

                        if (!APartnerInfoDS.Tables.Contains(PPartnerLocationTable.GetTableName()))
                        {
                            // Need to create Table here
                            APartnerInfoDS.Tables.Add(new PPartnerLocationTable());
                        }

                        // Add copies of the Location and PartnerLocation DataRows of the 'Best Address'

                        /*
                         * Remove DataColumns that might have been added by the call to
                         * TMailing.GetPartnersBestLocationData - otherwise PartnerLocationDR2.ItemArray
                         * assignment will fail.
                         */
                        if (PartnerLocationDR.Table.Columns.Contains(Calculations.PARTNERLOCATION_BESTADDR_COLUMN))
                        {
                            PartnerLocationDR.Table.Columns.Remove(Calculations.PARTNERLOCATION_BESTADDR_COLUMN);
                        }

                        if (PartnerLocationDR.Table.Columns.Contains(Calculations.PARTNERLOCATION_ICON_COLUMN))
                        {
                            PartnerLocationDR.Table.Columns.Remove(Calculations.PARTNERLOCATION_ICON_COLUMN);
                        }

                        LocationDR2                  = APartnerInfoDS.PLocation.NewRowTyped(false);
                        LocationDR2.ItemArray        = LocationDR.ItemArray;
                        PartnerLocationDR2           = APartnerInfoDS.PPartnerLocation.NewRowTyped(false);
                        PartnerLocationDR2.ItemArray = PartnerLocationDR.ItemArray;

                        APartnerInfoDS.PLocation.Rows.Add(LocationDR2);
                        APartnerInfoDS.PPartnerLocation.Rows.Add(PartnerLocationDR2);

                        #endregion

                        // Apply Address Security
                        LocationDT        = APartnerInfoDS.PLocation;
                        PartnerLocationDT = APartnerInfoDS.PPartnerLocation;

                        TPPartnerAddressAggregate.ApplySecurity(ref PartnerLocationDT,
                                                                ref LocationDT);

                        // Process 'Head' data and rest of data for the Partner
                        HeadInternal(PartnerDR, ref APartnerInfoDS);
                        RestInternal(PartnerDR, ref APartnerInfoDS, AReadTransaction);

                        ReturnValue = true;
                    }
                }
            }
            catch (ESecurityPartnerAccessDeniedException)
            {
                // don't log this exception - this is thrown on purpose here and the Client needs to deal with it.
                throw;
            }
            catch (Exception Exp)
            {
                TLogging.Log("TServerLookups_PartnerInfo.AllPartnerInfoData exception: " + Exp.ToString(), TLoggingType.ToLogfile);
                TLogging.Log(Exp.StackTrace, TLoggingType.ToLogfile);

                throw;
            }

            return(ReturnValue);
        }
 /// <summary>
 /// </summary>
 /// <param name="ALocationDT"></param>
 /// <param name="APartnerLocationDT"></param>
 /// <param name="APartnerKey"></param>
 /// <param name="APartnerClass"></param>
 /// <param name="ACountryCode"></param>
 /// <param name="ANewLocationKey"></param>
 /// <param name="ACopyFromPartnerLocationKey"></param>
 /// <param name="ACopyFromPartnerSiteKey"></param>
 /// <param name="ACopyFromFamilyPartnerKey"></param>
 /// <param name="ACopyFromFamilyLocationKey"></param>
 /// <param name="ACopyFromFamilySiteKey"></param>
 public static void CreateNewAddress(PLocationTable ALocationDT,
     PPartnerLocationTable APartnerLocationDT,
     Int64 APartnerKey,
     TPartnerClass APartnerClass,
     String ACountryCode,
     Int32 ANewLocationKey,
     Int32 ACopyFromPartnerLocationKey,
     Int64 ACopyFromPartnerSiteKey,
     Int64 ACopyFromFamilyPartnerKey,
     Int32 ACopyFromFamilyLocationKey,
     Int64 ACopyFromFamilySiteKey)
 {
     CreateNewAddress(ALocationDT,
         APartnerLocationDT,
         APartnerKey,
         APartnerClass,
         ACountryCode,
         ANewLocationKey,
         ACopyFromPartnerLocationKey,
         ACopyFromPartnerSiteKey,
         ACopyFromFamilyPartnerKey,
         ACopyFromFamilyLocationKey,
         ACopyFromFamilySiteKey,
         false,
         true);
 }