예제 #1
0
        /// <summary>
        /// Determines which address is the 'Best Address' of a Partner, and returns the PPartnerLocation record which is the
        /// 'Best Address'.
        /// </summary>
        /// <remarks>There are two similar shared Methods in Namespace Ict.Petra.Shared.MPartner.Calculations,
        /// both called 'DetermineBestAddress' which work by passing in the PartnerLocations of a Partner in an Argument
        /// and which return a <see cref="TLocationPK" />. As those Methods don't access the database, these Methods
        /// can be used client-side as well!</remarks>
        /// <param name="APartnerKey">PartnerKey of the Partner whose addresses should be checked.</param>
        /// <param name="APartnerLocationDR">PPartnerLocation Record that is the record that is the Location of the 'Best Address'.</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(Int64 APartnerKey, out PPartnerLocationRow APartnerLocationDR)
        {
            TLocationPK ReturnValue = new TLocationPK();
            PPartnerLocationTable PartnerLocationDT;
            Boolean NewTransaction;

            TDBTransaction ReadTransaction = DBAccess.GDBAccessObj.GetNewOrExistingTransaction(
                Ict.Petra.Server.MCommon.MCommonConstants.CACHEABLEDT_ISOLATIONLEVEL,
                TEnforceIsolationLevel.eilMinimum,
                out NewTransaction);

            try
            {
                PartnerLocationDT = PPartnerLocationAccess.LoadViaPPartner(APartnerKey, ReadTransaction);
                ReturnValue = Ict.Petra.Shared.MPartner.Calculations.DetermineBestAddress(PartnerLocationDT);

                APartnerLocationDR = (PPartnerLocationRow)PartnerLocationDT.Rows.Find(new object[]
                    { APartnerKey, ReturnValue.SiteKey, ReturnValue.LocationKey });
            }
            finally
            {
                if (NewTransaction)
                {
                    DBAccess.GDBAccessObj.CommitTransaction();
                    TLogging.LogAtLevel(7, "ServerCalculations.DetermineBestAddress: commited own transaction.");
                }
            }

            return ReturnValue;
        }
예제 #2
0
        /// <summary>
        /// Determines which address is the 'Best Address' of a Partner.
        /// </summary>
        /// <remarks>There are two similar shared Methods in Namespace Ict.Petra.Shared.MPartner.Calculations,
        /// both called 'DetermineBestAddress' which work by passing in the PartnerLocations of a Partner in an Argument
        /// and which return a <see cref="TLocationPK" />. As those Methods don't access the database, these Methods
        /// can be used client-side as well!</remarks>
        /// <param name="APartnerKey">PartnerKey of the Partner whose addresses should be checked.</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(Int64 APartnerKey)
        {
            TLocationPK BestLocation = new TLocationPK();
            PPartnerLocationRow Tmp;

            BestLocation = DetermineBestAddress(APartnerKey, out Tmp);

            return BestLocation;
        }
예제 #3
0
파일: Types.cs 프로젝트: weblate/openpetra
        /// <summary>
        /// Creates a 'deep' copy (i.e. not just copying of references but a real duplication of data)
        /// of a two-dimensional <see cref="TLocationPK" /> array, optionally exitending the resulting
        /// two-dimensional array by a number of empty array items.
        /// </summary>
        /// <param name="ASource">Two-dimensionaly <see cref="TLocationPK" /> array to copy from.</param>
        /// <param name="AExtendArrayByNEmptyItems">Specify the number of array items that you want the resulting array to be
        /// extended by (default = 0).</param>
        /// <returns>Deep Copy of <paramref name="ASource"/>, optionally extended by a number of empty array items.</returns>
        public static TLocationPK[, ] CopyTLocationPKArray(TLocationPK[, ] ASource, int AExtendArrayByNEmptyItems = 0)
        {
            TLocationPK[, ] ReturnValue = new TLocationPK[(ASource.Length / 2) + AExtendArrayByNEmptyItems, 2];

            for (int Counter = 0; Counter < ASource.Length / 2; Counter++)
            {
                ReturnValue[Counter, 0] = ASource[Counter, 0];
                ReturnValue[Counter, 1] = ASource[Counter, 1];
            }

            return(ReturnValue);
        }
예제 #4
0
        private void WriteLocation(PLocationRow ALocationRow, PPartnerLocationRow APartnerLocationRow,
            TLocationPK ABestAddressPK)
        {
            string PhoneNumber;
            string EmailAddress;
            string FaxNumber;

            Write(ALocationRow.IsSiteKeyNull() ? 0 : ALocationRow.SiteKey);
            Write(ALocationRow.IsLocalityNull() ? "" : ALocationRow.Locality);
            Write(ALocationRow.IsStreetNameNull() ? "" : ALocationRow.StreetName);
            Write(ALocationRow.IsAddress3Null() ? "" : ALocationRow.Address3);
            WriteLine();
            Write(ALocationRow.IsCityNull() ? "" : ALocationRow.City);
            Write(ALocationRow.IsCountyNull() ? "" : ALocationRow.County);
            Write(ALocationRow.IsPostalCodeNull() ? "" : ALocationRow.PostalCode);
            Write(ALocationRow.IsCountryCodeNull() ? "" : ALocationRow.CountryCode);
            WriteLine();

            Write(APartnerLocationRow.IsDateEffectiveNull() ? "?" : APartnerLocationRow.DateEffective.Value.ToString(DATEFORMAT));
            Write(APartnerLocationRow.IsDateGoodUntilNull() ? "?" : APartnerLocationRow.DateGoodUntil.Value.ToString(DATEFORMAT));
            Write(APartnerLocationRow.IsLocationTypeNull() ? "" : APartnerLocationRow.LocationType);
            Write(APartnerLocationRow.IsSendMailNull() ? false : APartnerLocationRow.SendMail);

            if ((APartnerLocationRow.LocationKey == ABestAddressPK.LocationKey)
                && (APartnerLocationRow.SiteKey == ABestAddressPK.SiteKey))
            {
                // For the Location that is the 'Best Address' of the Partner we export 'Primary Phone Number',
                // 'Primary E-mail Address' and the 'Fax Number'.
                // They are exported for backwards compatibility as part of the 'Location' information as that is the only
                // place where the data was/is stored (and was/is seen and was/is maintained by the user) in Petra 2.x!
                TContactDetailsAggregate.GetPrimaryEmailAndPrimaryPhoneAndFax(APartnerLocationRow.PartnerKey,
                    out PhoneNumber, out EmailAddress, out FaxNumber);

                Write(EmailAddress ?? String.Empty);
                Write(PhoneNumber ?? String.Empty);
                Write(0);  // Phone Extensions are no longer kept in the Contact Details scheme so we can't export them...
                Write(FaxNumber ?? String.Empty);
                Write(0);  // Fax Extensions are no longer kept in the Contact Details scheme so we can't export them...
            }
            else
            {
                // For any Location that isn't the 'Best Address' of the Partner: Export empty data for EmailAddress,
                // PhoneNumber, (Phone) Extension, Fax and Fax Extension.
                Write(String.Empty);
                Write(String.Empty);
                Write(0);
                Write(String.Empty);
                Write(0);
            }

            WriteLine();
        }
예제 #5
0
        /// <summary>
        /// Determines which address is the 'Best Address' of a Partner, and marks it in the DataColumn 'BestAddress'.
        /// </summary>
        /// <remarks>This method overload exists primarily for use in data migration from a legacy DB system.
        /// It gets called via .NET Reflection from Ict.Tools.DataDumpPetra2!
        /// DO NOT REMOVE THIS METHOD - although an IDE will not find any references to this Method!</remarks>
        /// <param name="APartnerLocationsDT">DataTable containing the addresses of a Partner.</param>
        /// <param name="ASiteKey">Site Key of the 'Best Address'.</param>
        /// <param name="ALocationKey">Location Key of the 'Best Address'.</param>
        /// <returns>True if a 'Best Address' was found, otherwise false.
        /// In the latter case ASiteKey and ALocationKey will be both -1, too.</returns>
        public static bool DetermineBestAddress(DataTable APartnerLocationsDT, out Int64 ASiteKey, out int ALocationKey)
        {
            TLocationPK PK = DetermineBestAddress(APartnerLocationsDT);

            if ((PK.SiteKey == -1) &&
                (PK.LocationKey == -1))
            {
                ASiteKey     = -1;
                ALocationKey = -1;

                return(false);
            }
            else
            {
                ASiteKey     = PK.SiteKey;
                ALocationKey = PK.LocationKey;

                return(true);
            }
        }
예제 #6
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);
        }
예제 #7
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);
        }
        /// <summary>
        /// todoComment
        /// </summary>
        private static TSubmitChangesResult PerformSimilarLocationReUseChecks(ref PLocationRow ALocationRow,
            ref PartnerAddressAggregateTDS AResponseDS,
            TDBTransaction ASubmitChangesTransaction,
            Int64 APartnerKey,
            ref PartnerAddressAggregateTDSSimilarLocationParametersTable AExistingLocationParametersDT,
            ref PPartnerLocationTable APartnerLocationTable,
            ref TLocationPK[, ] ALocationReUseKeyMapping,
            out Boolean AReUseSimilarLocation,
            ref TVerificationResultCollection AVerificationResult)
        {
            TSubmitChangesResult ReturnValue;
            PPartnerLocationRow PartnerLocationCheckRow;
            DataView ExistingLocationParametersDV;

            PLocationRow ExistingLocationRow;
            Int64 CurrentSiteKey;
            Int64 ExistingSiteKey;
            Int32 CurrentLocationKey;
            Int32 ExistingLocationKey;

            PLocationTable SimilarLocationDT;

//          TLogging.LogAtLevel(9, "PerformSimilarLocationReUseChecks: AExistingLocationParametersDT.Rows.Count: " +
//              AExistingLocationParametersDT.Rows.Count.ToString());
            AReUseSimilarLocation = false;

            if (CheckReUseExistingLocation(ALocationRow, APartnerKey, ref AExistingLocationParametersDT, ASubmitChangesTransaction,
                    out ExistingSiteKey, out ExistingLocationKey))
            {
                // 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() +
                    " AND " + PartnerAddressAggregateTDSSimilarLocationParametersTable.GetAnswerProcessedClientSideDBName() + " = false",
                    "",
                    DataViewRowState.CurrentRows);

                if (ExistingLocationParametersDV.Count > 0)
                {
//                  TLogging.LogAtLevel(9, "PerformSimilarLocationReUseChecks: Location " + ALocationRow.LocationKey.ToString() + ": found similar Location, decision 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, "PerformSimilarLocationReUseChecks: Creating AResponseDS.");
                        AResponseDS = new PartnerAddressAggregateTDS(MPartnerConstants.PARTNERADDRESSAGGREGATERESPONSE_DATASET);
                    }

//                  TLogging.LogAtLevel(9, "PerformSimilarLocationReUseChecks: AExistingLocationParametersDT.Rows.Count: " + AExistingLocationParametersDT.Rows.Count.ToString());
                    AResponseDS.Merge(AExistingLocationParametersDT);
//                  TLogging.LogAtLevel(9, "PerformSimilarLocationReUseChecks: Merged ExistingLocationParametersDT into AResponseDS.");
//                  TLogging.LogAtLevel(9, "PerformSimilarLocationReUseChecks: AResponseDS.Tables[" + MPartnerConstants.EXISTINGLOCATIONPARAMETERS_TABLENAME +
//                            "].Rows.Count: " + AResponseDS.Tables[MPartnerConstants.EXISTINGLOCATIONPARAMETERS_TABLENAME].Rows.Count.ToString());
                    return TSubmitChangesResult.scrInfoNeeded;
                }
                else
                {
//                  TLogging.LogAtLevel(9, "PerformSimilarLocationReUseChecks: Location " + ALocationRow.LocationKey.ToString() +
//                      ": found similar Location and this one (" + ExistingLocationKey.ToString() + ") should be used instead of creating a new one!");

                    /*
                     * Location with the same data already exists and it should be
                     * re-used instead of creating a new one!
                     */

                    // Keep a mapping of the initially submitted LocationKey to the newly assigned one
                    ALocationReUseKeyMapping = new TLocationPK[ALocationReUseKeyMapping.GetLength(0) + 1, 2];
                    ALocationReUseKeyMapping[(ALocationReUseKeyMapping.GetLength(0)) - 1, 0] = new TLocationPK(ALocationRow.SiteKey,
                        (int)ALocationRow.LocationKey);
                    ALocationReUseKeyMapping[(ALocationReUseKeyMapping.GetLength(0)) - 1, 1] = new TLocationPK(ExistingSiteKey, ExistingLocationKey);
                    AReUseSimilarLocation = true;

                    if (!AExistingLocationParametersDT[0].AnswerProcessedServerSide)
                    {
                        AExistingLocationParametersDT[0].AnswerProcessedServerSide = true;

                        // Preserve Key of current Location
                        CurrentSiteKey = ALocationRow.SiteKey;
                        CurrentLocationKey = (int)ALocationRow.LocationKey;

                        /*
                         * Make sure that the Partner hasn't already got a PartnerLocation with
                         * the same Key (neither in memory nor in the DB)
                         */
//                      TLogging.LogAtLevel(9, "PerformSimilarLocationReUseChecks: Finding PartnerLocation Row in APartnerLocationTable with LocationKey " + ALocationRow.LocationKey.ToString());
                        PartnerLocationCheckRow =
                            (PPartnerLocationRow)APartnerLocationTable.Rows.Find(new object[] { APartnerKey, ALocationRow.SiteKey,
                                                                                                ALocationRow.LocationKey });

                        if (PartnerLocationCheckRow != null)
                        {
                            /*
                             * Checks in Memory: look for Current (ie. unchanged, new or edited)
                             * rows first whether they are the Location that is about to being
                             * reused. Secondly, check if there is a deleted Location with the same
                             * LocationKey that is about to being reused; only if this is not the
                             * case:
                             * Check in the DB whether the Partner hasn't got the Location
                             * with the same LocationKey that is about to being reuse.
                             */
                            if ((APartnerLocationTable.Select(PPartnerLocationTable.GetPartnerKeyDBName() + " = " + APartnerKey.ToString() +
                                     " AND " + PPartnerLocationTable.GetSiteKeyDBName() + " = " + ExistingSiteKey.ToString() + " AND " +
                                     PPartnerLocationTable.GetLocationKeyDBName() + " = " + ExistingLocationKey.ToString(), "",
                                     DataViewRowState.CurrentRows).Length != 0)
                                || ((APartnerLocationTable.Select(PPartnerLocationTable.GetPartnerKeyDBName() + " = " + APartnerKey.ToString() +
                                         " AND " +
                                         PPartnerLocationTable.GetSiteKeyDBName() + " = " + ExistingSiteKey.ToString() + " AND " +
                                         PPartnerLocationTable.GetLocationKeyDBName() + " = " + ExistingLocationKey.ToString(), "",
                                         DataViewRowState.Deleted).Length == 0)
                                    && (PPartnerLocationAccess.Exists(APartnerKey, ExistingSiteKey, ExistingLocationKey,
                                            ASubmitChangesTransaction))))
                            {
                                AVerificationResult.Add(new TVerificationResult("[Partner Address Save]", "Partner " + APartnerKey.ToString() +
                                        " already has a " + "record linked with Location " + ExistingLocationKey.ToString() + Environment.NewLine +
                                        "Unable to save.", "Duplicate Address Entered", "", TResultSeverity.Resv_Critical));
                                ReturnValue = TSubmitChangesResult.scrError;
                                return ReturnValue;
                            }
                            else
                            {
//                              TLogging.LogAtLevel(9, "PerformSimilarLocationReUseChecks: LocationKey: " + ExistingLocationKey.ToString() + " will later get assigned to PPartnerLocation.");
                            }
                        }
                        else
                        {
                            throw new EOPAppException(
                                "PerformSimilarLocationReUseChecks: PartnerLocationCheckRow with SiteKey " + ALocationRow.SiteKey.ToString() +
                                " and LocationKey " +
                                ALocationRow.LocationKey.ToString() + " not found!");
                        }

                        /*
                         * Copy all fields from the existing Location to the current Location
                         */
                        SimilarLocationDT = PLocationAccess.LoadByPrimaryKey(ExistingSiteKey, ExistingLocationKey, null, ASubmitChangesTransaction);

                        if (SimilarLocationDT.Rows.Count != 0)
                        {
                            ExistingLocationRow = (PLocationRow)SimilarLocationDT.Rows[0];

                            ALocationRow.ItemArray = ExistingLocationRow.ItemArray;

                            /*
                             * NOTE: The SiteKey and LocationKey are re-assigned to the ones of the
                             * current Location. This is done to have the current SiteKey and
                             * LocationKey preserved throughout the whole process of working with the
                             * Locations. The SiteKey and LocationKey are exchanged with the ones of
                             * the existing Location before the DataRow gets sent back to the Client!
                             */
                            ALocationRow.SiteKey = CurrentSiteKey;
                            ALocationRow.LocationKey = CurrentLocationKey;
//                          TLogging.LogAtLevel(9, "CheckReUseExistingLocation: Location " + ALocationRow.LocationKey.ToString() +
//                                ": data got replaced with data from the existing Location (" + ExistingLocationKey.ToString() + ")!");
                        }
                        else
                        {
                            throw new EOPAppException(
                                "Couldn''t find existing Similar Location with SiteKey " + ALocationRow.SiteKey.ToString() + " and LocationKey " +
                                ALocationRow.LocationKey.ToString() + '!');
                        }
                    }
                }
            }
            else
            {
//              TLogging.LogAtLevel(9, "CheckReUseExistingLocation: Location " + ALocationRow.LocationKey.ToString() +
//                  ": Location does not exist yet (or an existing Location should not be re-used) -> will get saved later.");

                /*
                 * No similar Location exists, or an existing similar Location should
                 * not be re-used: Save this Location
                 * -> will get saved later in call to SubmitChanges
                 */
            }

            return TSubmitChangesResult.scrOK;
        }
        /// <summary>
        /// todoComment
        /// </summary>
        /// <param name="ARow"></param>
        /// <param name="AExistingLocationParametersDT"></param>
        /// <returns></returns>
        private static TLocationPK DetermineReplacedLocationPK(DataRow ARow,
            PartnerAddressAggregateTDSSimilarLocationParametersTable AExistingLocationParametersDT)
        {
            TLocationPK ReturnValue;
            Int64 SiteKey;
            Int32 LocationKey;
            PartnerAddressAggregateTDSSimilarLocationParametersRow ExistingLocationParametersDR;
            DataView ExistingLocationParametersDV;

            ReturnValue = null;

            if (!((ARow is PLocationRow) || (ARow is PPartnerLocationRow)))
            {
                throw new System.ArgumentException("ARow Argument must be either of Type PLocationRow or of Type PPartnerLocationRow");
            }

            if (ARow is PLocationRow)
            {
                SiteKey = ((PLocationRow)ARow).SiteKey;
                LocationKey = (int)((PLocationRow)ARow).LocationKey;
            }
            else
            {
                SiteKey = ((PPartnerLocationRow)ARow).SiteKey;
                LocationKey = ((PPartnerLocationRow)ARow).LocationKey;
            }

            if ((AExistingLocationParametersDT != null) && (AExistingLocationParametersDT.Rows.Count > 0))
            {
//              TLogging.LogAtLevel(9, "DetermineReplacedLocationPK: checking for LocationKey: " + LocationKey.ToString());

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

                if (ExistingLocationParametersDV.Count != 0)
                {
//                  TLogging.LogAtLevel(9, "DetermineReplacedLocationPK: Key found in AExistingLocationParametersDT");
                    ExistingLocationParametersDR = (PartnerAddressAggregateTDSSimilarLocationParametersRow)ExistingLocationParametersDV[0].Row;
                    ReturnValue =
                        new TLocationPK(Convert.ToInt64(ExistingLocationParametersDR[PartnerAddressAggregateTDSSimilarLocationParametersTable.
                                                                                     GetSiteKeyDBName(),
                                                                                     DataRowVersion.Original]),
                            Convert.ToInt32(ExistingLocationParametersDR[PartnerAddressAggregateTDSSimilarLocationParametersTable.
                                                                         GetLocationKeyDBName(),
                                                                         DataRowVersion.Original]));
                }
            }

            if (ReturnValue == null)
            {
                // passed in Key not found in AExistingLocationParametersDT
//              TLogging.LogAtLevel(9, "DetermineReplacedLocationPK: Key *not* found in AExistingLocationParametersDT");
                ReturnValue = new TLocationPK(SiteKey, LocationKey);
            }

//          TLogging.LogAtLevel(9, "DetermineReplacedLocationPK: Result.SiteKey: " + ReturnValue.SiteKey.ToString() + "; ReturnValue.LocationKey: " + ReturnValue.LocationKey.ToString());
            return ReturnValue;
        }
        /// <summary>
        /// todoComment
        /// </summary>
        /// <param name="ALocationRow"></param>
        /// <param name="AOriginalLocationKey"></param>
        /// <param name="AExistingLocationParametersDT"></param>
        private static void ModifyExistingLocationParameters(PLocationRow ALocationRow,
            TLocationPK AOriginalLocationKey,
            ref PartnerAddressAggregateTDSSimilarLocationParametersTable AExistingLocationParametersDT)
        {
            DataView ExistingLocationParametersDV;
            PartnerAddressAggregateTDSSimilarLocationParametersRow SimilarLocationParameterRow;

//          TLogging.LogAtLevel(9, "ModifyExistingLocationParameters: Looking for ExistingLocationParameters with LocationKey " +
//              AOriginalLocationKey.LocationKey.ToString() + "; AExistingLocationParametersDT.Rows.Count: " + AExistingLocationParametersDT.Rows.Count.ToString());

/* if DEBUGMODE
 *          if (TLogging.DL >= 8)
 *          {
 *              for (int TmpRowCounter = 0; TmpRowCounter <= AExistingLocationParametersDT.Rows.Count - 1; TmpRowCounter += 1)
 *              {
 *                  TLogging.Log("Checking Row: " + TmpRowCounter.ToString());
 *                  TLogging.Log("ModifyExistingLocationParameters: SimilarLocationParameterRow[" + TmpRowCounter.ToString() + ".RowState: " +
 *                      (Enum.GetName(typeof(DataRowState), AExistingLocationParametersDT.Rows[TmpRowCounter].RowState)));
 *                  TLogging.Log(
 *                      "ModifyExistingLocationParameters: before searching: Row[" + TmpRowCounter.ToString() + "]: PLocationKey: " +
 *                      AExistingLocationParametersDT[TmpRowCounter][PartnerAddressAggregateTDSSimilarLocationParametersTable.GetLocationKeyDBName(),
 *                                                                   DataRowVersion.Current].ToString() + "; PSiteKey: " +
 *                      AExistingLocationParametersDT[TmpRowCounter][PartnerAddressAggregateTDSSimilarLocationParametersTable.GetSiteKeyDBName(),
 *                                                                   DataRowVersion.Current].ToString() + "; RowState: " +
 *                      (Enum.GetName(typeof(DataRowState), AExistingLocationParametersDT.Rows[TmpRowCounter].RowState)));
 *              }
 *          }
 */

            if (AExistingLocationParametersDT.Rows.Count != 0)
            {
                // Check if there is a Parameter Row for the LocationKey we are looking at
                // ExistingLocationParametersDV := new DataView(
                // AExistingLocationParametersDT,
                // PartnerAddressAggregateTDSSimilarLocationParametersTable.GetSiteKeyDBName +
                // ' = ' + Convert.ToInt64(ALocationRow[PLocationTable.GetSiteKeyDBName,
                // DataRowVersion.Original]).ToString +
                // ' AND ' +
                // PartnerAddressAggregateTDSSimilarLocationParametersTable.GetLocationKeyDBName +
                // ' = ' + Convert.ToInt32(ALocationRow[PLocationTable.GetLocationKeyDBName,
                // DataRowVersion.Original]).ToString, '', DataViewRowState.OriginalRows);
                ExistingLocationParametersDV = new DataView(AExistingLocationParametersDT,
                    PartnerAddressAggregateTDSSimilarLocationParametersTable.GetSiteKeyDBName() + " = " + AOriginalLocationKey.SiteKey.ToString() +
                    " AND " + PartnerAddressAggregateTDSSimilarLocationParametersTable.GetLocationKeyDBName() + " = " +
                    AOriginalLocationKey.LocationKey.ToString(),
                    "",
                    DataViewRowState.ModifiedOriginal);

                // There is a row like that: replace SiteKey and LocationKey!
                if (ExistingLocationParametersDV.Count != 0)
                {
                    SimilarLocationParameterRow = (PartnerAddressAggregateTDSSimilarLocationParametersRow)ExistingLocationParametersDV[0].Row;
//                  TLogging.LogAtLevel(9, "ModifyExistingLocationParameters: Exchanging LocationKey " + SimilarLocationParameterRow.LocationKey.ToString() +
//                      " with LocationKey " + ALocationRow.LocationKey.ToString());

/* if DEBUGMODE
 *                  if (TLogging.DL >= 8)
 *                  {
 *                      TLogging.Log("ModifyExistingLocationParameters: SimilarLocationParameterRow.RowState: " +
 *                          (Enum.GetName(typeof(DataRowState), SimilarLocationParameterRow.RowState)));
 *
 *                      if (SimilarLocationParameterRow.RowState == DataRowState.Added)
 *                      {
 *                          TLogging.Log("ModifyExistingLocationParameters (before modification): PLocationKey: " +
 *                              SimilarLocationParameterRow[PartnerAddressAggregateTDSSimilarLocationParametersTable.GetLocationKeyDBName()].ToString(
 *                                  ) +
 *                              "; PSiteKey: " +
 *                              SimilarLocationParameterRow[PartnerAddressAggregateTDSSimilarLocationParametersTable.GetSiteKeyDBName()].ToString() +
 *                              "; RowState: " + (Enum.GetName(typeof(DataRowState), SimilarLocationParameterRow.RowState)));
 *                      }
 *                      else if ((SimilarLocationParameterRow.RowState == DataRowState.Modified)
 || (SimilarLocationParameterRow.RowState == DataRowState.Unchanged))
 ||                     {
 ||                         TLogging.Log("ModifyExistingLocationParameters (before modification): PLocationKey: " +
 ||                             SimilarLocationParameterRow[PartnerAddressAggregateTDSSimilarLocationParametersTable.GetLocationKeyDBName(),
 ||                                                         DataRowVersion.Original].ToString() + "; PSiteKey: " +
 ||                             SimilarLocationParameterRow[PartnerAddressAggregateTDSSimilarLocationParametersTable.GetSiteKeyDBName(),
 ||                                                         DataRowVersion.Original].ToString() + "; RowState: " +
 ||                             (Enum.GetName(typeof(DataRowState), SimilarLocationParameterRow.RowState) + " (ORIGINAL)"));
 ||                         TLogging.Log("ModifyExistingLocationParameters (before modification): PLocationKey: " +
 ||                             SimilarLocationParameterRow[PartnerAddressAggregateTDSSimilarLocationParametersTable.GetLocationKeyDBName(),
 ||                                                         DataRowVersion.Current].ToString() + "; PSiteKey: " +
 ||                             SimilarLocationParameterRow[PartnerAddressAggregateTDSSimilarLocationParametersTable.GetSiteKeyDBName(),
 ||                                                         DataRowVersion.Current].ToString() + "; RowState: " +
 ||                             (Enum.GetName(typeof(DataRowState), SimilarLocationParameterRow.RowState) + " (CURRENT)"));
 ||                     }
 ||                 }
 */

                    // Now modify it so that it can be found later by function DetermineReplacedLocationPK!
                    SimilarLocationParameterRow.SiteKey = ALocationRow.SiteKey;
                    SimilarLocationParameterRow.LocationKey = ALocationRow.LocationKey;

/* if DEBUGMODE
 *                  if (TLogging.DL >= 8)
 *                  {
 *                      TLogging.Log("ModifyExistingLocationParameters: SimilarLocationParameterRow.RowState: " +
 *                          (Enum.GetName(typeof(DataRowState), SimilarLocationParameterRow.RowState)));
 *
 *                      if (SimilarLocationParameterRow.RowState == DataRowState.Added)
 *                      {
 *                          TLogging.Log("ModifyExistingLocationParameters (after modification): PLocationKey: " +
 *                              SimilarLocationParameterRow[PartnerAddressAggregateTDSSimilarLocationParametersTable.GetLocationKeyDBName()].ToString(
 *                                  ) +
 *                              "; PSiteKey: " +
 *                              SimilarLocationParameterRow[PartnerAddressAggregateTDSSimilarLocationParametersTable.GetSiteKeyDBName()].ToString() +
 *                              "; RowState: " + (Enum.GetName(typeof(DataRowState), SimilarLocationParameterRow.RowState)));
 *                      }
 *                      else if ((SimilarLocationParameterRow.RowState == DataRowState.Modified)
 || (SimilarLocationParameterRow.RowState == DataRowState.Unchanged))
 ||                     {
 ||                         TLogging.Log("ModifyExistingLocationParameters (after modification): PLocationKey: " +
 ||                             SimilarLocationParameterRow[PartnerAddressAggregateTDSSimilarLocationParametersTable.GetLocationKeyDBName(),
 ||                                                         DataRowVersion.Original].ToString() + "; PSiteKey: " +
 ||                             SimilarLocationParameterRow[PartnerAddressAggregateTDSSimilarLocationParametersTable.GetSiteKeyDBName(),
 ||                                                         DataRowVersion.Original].ToString() + "; RowState: " +
 ||                             (Enum.GetName(typeof(DataRowState), SimilarLocationParameterRow.RowState) + " (ORIGINAL)"));
 ||                         TLogging.Log("ModifyExistingLocationParameters (after modification): PLocationKey: " +
 ||                             SimilarLocationParameterRow[PartnerAddressAggregateTDSSimilarLocationParametersTable.GetLocationKeyDBName(),
 ||                                                         DataRowVersion.Current].ToString() + "; PSiteKey: " +
 ||                             SimilarLocationParameterRow[PartnerAddressAggregateTDSSimilarLocationParametersTable.GetSiteKeyDBName(),
 ||                                                         DataRowVersion.Current].ToString() + "; RowState: " +
 ||                             (Enum.GetName(typeof(DataRowState), SimilarLocationParameterRow.RowState) + " (CURRENT)"));
 ||                     }
 ||                 }
 */
                }
            }
            else
            {
//              TLogging.LogAtLevel(9, "ModifyExistingLocationParameters: No ExistingLocationParameters with LocationKey " + AOriginalLocationKey.LocationKey.ToString() + " found --> creating new one!");

                /*
                 * No such parameter row found -> create a 'fake' one!
                 *
                 * NOTE: This is a bit of a 'Hack', since normally only function
                 * CheckReUseExistingLocation creates such a DataRow. However, currently
                 * this 'Hack' is needed to make function DetermineReplacedLocationPK work
                 * even if function CheckReUseExistingLocation was never executed (because
                 * no similar Location was found)...
                 */
                SimilarLocationParameterRow = AExistingLocationParametersDT.NewRowTyped(false);
                SimilarLocationParameterRow.SiteKey = AOriginalLocationKey.SiteKey;
                SimilarLocationParameterRow.LocationKey = AOriginalLocationKey.LocationKey;
                SimilarLocationParameterRow.UsedByNOtherPartners = 0;
                SimilarLocationParameterRow.SiteKeyOfSimilarLocation = ALocationRow.SiteKey;
                SimilarLocationParameterRow.LocationKeyOfSimilarLocation = (int)ALocationRow.LocationKey;
                SimilarLocationParameterRow.AnswerProcessedClientSide = true;
                SimilarLocationParameterRow.AnswerProcessedServerSide = true;
                SimilarLocationParameterRow.AnswerReuse = false;
                AExistingLocationParametersDT.Rows.Add(SimilarLocationParameterRow);
                SimilarLocationParameterRow.AcceptChanges();

                // Now modify it so that it can be found later by function DetermineReplacedLocationPK!
                SimilarLocationParameterRow.SiteKey = ALocationRow.SiteKey;
                SimilarLocationParameterRow.LocationKey = ALocationRow.LocationKey;
            }
        }
        /// <summary>
        ///  Check each PartnerLocation DataRow before calling SubmitChanges
        ///  to enforce Business Rules:
        ///  - Added PartnerLocation:
        ///  - if working with a PartnerLocation of a FAMILY:
        ///  - Added PartnerLocation: if working with a Location of a FAMILY: allow
        ///  choosing whether this PartnerLocation should be added to all PERSONs
        ///  in the FAMILY
        ///  - make sure that Location 0 is no longer mapped to this Partner.
        ///  - Modified Location:
        ///  - if working with a PartnerLocation of a FAMILY:
        ///  - check whether other Partners are referencing it, and if so,
        ///  allow choosing which of the Partners (or none or all) should be
        ///  affected by the change
        ///  - if the value in the DateGoodUntil column has changed, silently
        ///  update it for all PERSONs of a FAMILY that have the same LocationKey.
        ///  - Deleted PartnerLocation: check whether this is the last
        ///  PartnerLocation that is left for this Partner. If this is the case,
        ///  don't delete the PartnerLocation, but set it's LocationKey to 0.
        /// </summary>
        private static TSubmitChangesResult ProcessPartnerLocationChanges(
            PPartnerLocationTable PartnerLocationTable,
            ref PartnerAddressAggregateTDS AResponseDS,
            TDBTransaction ASubmitChangesTransaction,
            Int64 APartnerKey,
            String APartnerClass,
            ref TLocationPK[, ] ASimilarLocationReUseKeyMapping,
            ref PartnerAddressAggregateTDSSimilarLocationParametersTable AExistingLocationParametersDT,
            ref PartnerAddressAggregateTDSAddressAddedOrChangedPromotionTable AAddressAddedOrChangedPromotionParametersDT,
            ref PartnerAddressAggregateTDSChangePromotionParametersTable AChangeLocationParametersDT,
            ref TVerificationResultCollection AVerificationResult)
        {
            TSubmitChangesResult Result = TSubmitChangesResult.scrOK;
            TSubmitChangesResult TmpResult;

            for (Int16 PartnerLocationCounter = 0; PartnerLocationCounter <= PartnerLocationTable.Rows.Count - 1; PartnerLocationCounter += 1)
            {
                switch (PartnerLocationTable.Rows[PartnerLocationCounter].RowState)
                {
                    case DataRowState.Added:

                        if (PartnerLocationTable[PartnerLocationCounter].LocationKey != 0)
                        {
                            /*
                             * PartnerLocation of a FAMILY: Family Members promotion
                             */
                            if (APartnerClass == SharedTypes.PartnerClassEnumToString(TPartnerClass.FAMILY))
                            {
                                bool PerformPropagation = false;

                                TmpResult = PerformLocationFamilyMemberPropagationChecks(
                                    PartnerLocationTable[PartnerLocationCounter],
                                    ref AResponseDS,
                                    ASubmitChangesTransaction,
                                    APartnerKey,
                                    APartnerClass,
                                    ref AAddressAddedOrChangedPromotionParametersDT,
                                    ref PartnerLocationTable,
                                    AExistingLocationParametersDT,
                                    ASimilarLocationReUseKeyMapping,
                                    out PerformPropagation,
                                    ref AVerificationResult);

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

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

                                if (PerformPropagation)
                                {
                                    ModifyAddressAddedOrChangedParameters(PartnerLocationTable[PartnerLocationCounter],
                                        ref AAddressAddedOrChangedPromotionParametersDT);
                                }
                            }

                            /*
                             * Since a new Location has been added, we need to make sure that
                             * Location 0 is no longer mapped to this Partner!
                             */
                            MakeSureLocation0IsNotPresent(APartnerKey,
                                PartnerLocationTable[PartnerLocationCounter].SiteKey,
                                PartnerLocationTable,
                                ASubmitChangesTransaction);
                        }
                        else
                        {
                            MakeSureLocation0SavingIsAllowed(PartnerLocationTable[PartnerLocationCounter],
                                APartnerKey,
                                ASubmitChangesTransaction);
                        }

                        break;

                    case DataRowState.Modified:

                        /*
                         * PartnerLocation of a FAMILY: Family Members promotion
                         */
                        if (APartnerClass == SharedTypes.PartnerClassEnumToString(TPartnerClass.FAMILY))
                        {
                            /*
                             * If the value in the DateGoodUntil column has changed, silently
                             * update it for all PERSONs of this FAMILY that have the same
                             * LocationKey.
                             */
                            if (TSaveConvert.ObjectToDate(PartnerLocationTable[PartnerLocationCounter][PPartnerLocationTable.
                                                                                                       GetDateGoodUntilDBName(),
                                                                                                       DataRowVersion.Original]) !=
                                TSaveConvert.ObjectToDate(PartnerLocationTable[PartnerLocationCounter][PPartnerLocationTable.
                                                                                                       GetDateGoodUntilDBName(),
                                                                                                       DataRowVersion.Current]))
                            {
//                              TLogging.LogAtLevel(8, "SubmitChanges: PartnerLocation of a FAMILY: DateGoodUntil has changed -> promoting change to FAMILY members...");

                                PromoteToFamilyMembersDateGoodUntilChange(APartnerKey, PartnerLocationTable[PartnerLocationCounter],
                                    ASubmitChangesTransaction);
                            }
                        }

                        break;

                    case DataRowState.Deleted:

                        /*
                         * PPartnerLocation must not get deleted if it is the last one of the
                         * Partner, but must get mapped to Location 0 instead!
                         */

                        // Make sure that Location 0 can never get deleted!
                        if (Convert.ToInt32(PartnerLocationTable[PartnerLocationCounter][PPartnerLocationTable.GetLocationKeyDBName(),
                                                                                         DataRowVersion.Original]) != 0)
                        {
                            // Some other Location than Location 0 is about to be deleted!
                            // Check in the in-memory PartnerLocation Table first...
                            DataRow[] ChangePartnerLocationKeyRows = PartnerLocationTable.Select(
                                PPartnerLocationTable.GetPartnerKeyDBName() + " = " + APartnerKey.ToString() + " AND " +
                                PPartnerLocationTable.GetLocationKeyDBName() + " <> " +
                                PartnerLocationTable[PartnerLocationCounter][PPartnerLocationTable.GetLocationKeyDBName(),
                                                                             DataRowVersion.Original].ToString(), "",
                                DataViewRowState.CurrentRows);

                            if (ChangePartnerLocationKeyRows.Length == 0)
                            {
                                // No PPartnerLocation that is not deleted is left in
                                // PartnerLocationTable > now check for deleted ones
                                DataView DeletedPartnerLocationsDV = new DataView(PartnerLocationTable, "", "", DataViewRowState.Deleted);
                                int[] DeletedPartnerLocationKeys = new int[DeletedPartnerLocationsDV.Count];

                                for (Int16 DeletedPartnerLocationsCounter = 0;
                                     DeletedPartnerLocationsCounter <= DeletedPartnerLocationsDV.Count - 1;
                                     DeletedPartnerLocationsCounter += 1)
                                {
                                    DeletedPartnerLocationKeys[DeletedPartnerLocationsCounter] =
                                        Convert.ToInt32(DeletedPartnerLocationsDV[DeletedPartnerLocationsCounter].Row[PPartnerLocationTable.
                                                                                                                      GetLocationKeyDBName(),
                                                                                                                      DataRowVersion.Original
                                            ]);
                                }

                                // now check in the DB as well
                                if (!CheckHasPartnerOtherPartnerLocations(DeletedPartnerLocationKeys, APartnerKey, ASubmitChangesTransaction))
                                {
                                    // 'Undelete' DataRow and make it point to Location 0
                                    // (dummy Location) > will get submitted lateron!
                                    PartnerLocationTable[PartnerLocationCounter].RejectChanges();
                                    PartnerLocationTable[PartnerLocationCounter].LocationKey = 0;
//                                  TLogging.LogAtLevel(8, "SubmitChanges: PPartnerLocation " +
//                                      PartnerLocationTable[PartnerLocationCounter][PPartnerLocationTable.GetLocationKeyDBName(),
//                                      DataRowVersion.Original].ToString() + ": was last PartnerLocation, so its LocationKey got set to 0 (will be submitted lateron)!");
                                }
                            }
                            else
                            {
                                // There is at least one PPartnerLocation that is not deleted
                                // left in PartnerLocationTable, so the current PPartnerLocation
                                // can't be the last one > nothing to do.
                            }
                        }
                        else
                        {
                            DataRow[] ChangePartnerLocationKeyRows = PartnerLocationTable.Select(
                                PPartnerLocationTable.GetPartnerKeyDBName() + " = " + APartnerKey.ToString() + " AND " +
                                PPartnerLocationTable.GetLocationKeyDBName() + " = 0 ", "", DataViewRowState.CurrentRows);
//                          TLogging.LogAtLevel(8, "SubmitChanges: ChangePartnerLocationKeyRows Length: " + Convert.ToInt16(ChangePartnerLocationKeyRows.Length).ToString());

                            if (ChangePartnerLocationKeyRows.Length != 0)
                            {
                                // remove this location because it should not be submitted to the database
                                PartnerLocationTable.Rows.RemoveAt(PartnerLocationCounter);
                                PartnerLocationCounter--;

//                              TLogging.LogAtLevel(8, "SubmitChanges: Extra Location 0 row won''t be submitted lateron");
                            }
                        }

                        break;

                    case DataRowState.Unchanged:
                        break;

                    default:
                        throw new ArgumentException(
                        "SubmitChanges can only deal with PartnerLocations of DataRowState Added, Modified or Deleted, but not with " +
                        (Enum.GetName(typeof(DataRowState), PartnerLocationTable.Rows[PartnerLocationCounter].RowState)));
                }
            }

            return Result;
        }
        /// <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;
        }
예제 #13
0
        public static Boolean VerifyPartnerAtLocation(Int64 APartnerKey,
            TLocationPK ALocationKey, out bool AAddressNeitherCurrentNorMailing)
        {
            AAddressNeitherCurrentNorMailing = true;

            TDBTransaction ReadTransaction;
            Boolean NewTransaction;
            PPartnerLocationTable PartnerLocationTable;
            Boolean ReturnValue = true;

            ReadTransaction = DBAccess.GDBAccessObj.GetNewOrExistingTransaction(IsolationLevel.ReadCommitted,
                TEnforceIsolationLevel.eilMinimum,
                out NewTransaction);
            try
            {
                PartnerLocationTable = PPartnerLocationAccess.LoadByPrimaryKey(APartnerKey,
                    ALocationKey.SiteKey,
                    ALocationKey.LocationKey,
                    ReadTransaction);
            }
            finally
            {
                if (NewTransaction)
                {
                    DBAccess.GDBAccessObj.CommitTransaction();
                }
            }

            if (PartnerLocationTable.Rows.Count == 0)
            {
                ReturnValue = false;
            }
            else
            {
                PPartnerLocationRow Row = (PPartnerLocationRow)PartnerLocationTable.Rows[0];

                // check if the partner location is either current or if it is a mailing address
                if ((Row.DateEffective > DateTime.Today)
                    || (!Row.SendMail)
                    || ((Row.DateGoodUntil != null)
                        && (Row.DateGoodUntil < DateTime.Today)))
                {
                    AAddressNeitherCurrentNorMailing = true;
                }
                else
                {
                    AAddressNeitherCurrentNorMailing = false;
                }

                ReturnValue = true;
            }

            return ReturnValue;
        }
예제 #14
0
        /// <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);
        }
        /// <summary>
        /// Returns the values of the found partner.
        /// </summary>
        /// <param name="APartnerKey">Partner key</param>
        /// <param name="AShortName">Partner short name</param>
        /// <param name="APartnerClass">Partner Class.</param>
        /// <param name="ALocationPK">Location key</param>
        /// <param name="ABankingDetailsKey">Location key</param>
        /// <returns></returns>
        public Boolean GetReturnedParameters(out Int64 APartnerKey, out String AShortName, out TPartnerClass? APartnerClass,
            out TLocationPK ALocationPK, out int ABankingDetailsKey)
        {
            DataRowView[] SelectedGridRow = grdResult.SelectedDataRowsAsDataRowView;

            if (SelectedGridRow.Length <= 0)
            {
                // no Row is selected
                APartnerKey = -1;
                AShortName = "";
                APartnerClass = null;
                ALocationPK = new TLocationPK(-1, -1);
                ABankingDetailsKey = -1;
            }
            else
            {
                // MessageBox.Show(SelectedGridRow[0]['p_partner_key_n'].ToString);
                APartnerKey = Convert.ToInt64(SelectedGridRow[0][PPartnerTable.GetPartnerKeyDBName()]);
                AShortName = Convert.ToString(SelectedGridRow[0][PPartnerTable.GetPartnerShortNameDBName()]);
                APartnerClass = SharedTypes.PartnerClassStringToEnum(Convert.ToString(SelectedGridRow[0][PPartnerTable.GetPartnerClassDBName()]));

                if (!FBankDetailsTab)
                {
                    ALocationPK =
                        new TLocationPK(Convert.ToInt64(SelectedGridRow[0][PPartnerLocationTable.GetSiteKeyDBName()]),
                            Convert.ToInt32(SelectedGridRow[0][PPartnerLocationTable.GetLocationKeyDBName()]));

                    ABankingDetailsKey = -1;
                }
                else
                {
                    ABankingDetailsKey = Convert.ToInt32(SelectedGridRow[0][PBankingDetailsTable.GetBankingDetailsKeyDBName()]);

                    ALocationPK = null;
                }
            }

            return true;
        }
예제 #16
0
        /// <summary>
        /// Determine best location for partner out of a list of possible locations. Or simply find best one
        /// if no suggestion is made.
        /// </summary>
        /// <param name="APartnerKey"></param>
        /// <param name="ALocationKeyList"></param>
        /// <param name="APartnerLocationKeysTable"></param>
        /// <param name="ATransaction"></param>
        /// <returns>True if the address was found and added, otherwise false.</returns>
        private static Boolean DetermineAndAddBestLocationKey(
            Int64 APartnerKey,
            List <TLocationPK>ALocationKeyList,
            ref PPartnerLocationTable APartnerLocationKeysTable,
            TDBTransaction ATransaction)
        {
            PPartnerLocationTable AllPartnerLocationTable;
            PPartnerLocationTable FilteredPartnerLocationTable = new PPartnerLocationTable();
            TLocationPK LocationPK = new TLocationPK();
            PPartnerLocationRow PartnerLocationKeyRow;
            PPartnerLocationRow PartnerLocationRowCopy;
            TLocationPK BestLocationPK;

            if (ALocationKeyList.Count == 0)
            {
                // no list suggested: find best address in db for this partner
                BestLocationPK = TMailing.GetPartnersBestLocation(APartnerKey);
            }
            else if (ALocationKeyList.Count == 1)
            {
                // only one location suggested: take this one
                BestLocationPK = ALocationKeyList[0];
            }
            else
            {
                // Process location key list related to partner.
                // In order to use Calculations.DetermineBestAddress we need to first retrieve full data
                // for all suggested records from the db. Therefore load all locations for this partner
                // and then create a table of the ones that are suggested.
                AllPartnerLocationTable = PPartnerLocationAccess.LoadViaPPartner(APartnerKey, ATransaction);

                foreach (PPartnerLocationRow PartnerLocationRow in AllPartnerLocationTable.Rows)
                {
                    LocationPK.SiteKey = PartnerLocationRow.SiteKey;
                    LocationPK.LocationKey = PartnerLocationRow.LocationKey;

                    if (ALocationKeyList.Contains(LocationPK))
                    {
                        PartnerLocationRowCopy = (PPartnerLocationRow)FilteredPartnerLocationTable.NewRow();
                        DataUtilities.CopyAllColumnValues(PartnerLocationRow, PartnerLocationRowCopy);
                        FilteredPartnerLocationTable.Rows.Add(PartnerLocationRowCopy);
                    }
                }

                BestLocationPK = Calculations.DetermineBestAddress(FilteredPartnerLocationTable);
            }

            // create new row, initialize it and add it to the table
            if (BestLocationPK.LocationKey != -1)
            {
                PartnerLocationKeyRow = (PPartnerLocationRow)APartnerLocationKeysTable.NewRow();
                PartnerLocationKeyRow[PPartnerLocationTable.GetPartnerKeyDBName()] = APartnerKey;
                PartnerLocationKeyRow[PPartnerLocationTable.GetSiteKeyDBName()] = BestLocationPK.SiteKey;
                PartnerLocationKeyRow[PPartnerLocationTable.GetLocationKeyDBName()] = BestLocationPK.LocationKey;

                // only add row if it does not already exist
                if (!APartnerLocationKeysTable.Rows.Contains(
                        new object[] { PartnerLocationKeyRow.PartnerKey, PartnerLocationKeyRow.SiteKey, PartnerLocationKeyRow.LocationKey }))
                {
                    APartnerLocationKeysTable.Rows.Add(PartnerLocationKeyRow);
                }

                return true;
            }
            else
            {
                return false;
            }
        }
예제 #17
0
        /// <summary>
        /// Returns the Primary Key of the Location and the Location and PartnerLocation DataRows
        /// of the 'Best Address' of a Partner.
        /// </summary>
        /// <param name="APartnerKey">PartnerKey of the Partner for which the 'Best Address'
        /// should be loaded for.</param>
        /// <param name="ABestAddressPK">Primary Key of the 'Best Address' Location</param>
        /// <param name="ALocationDR">DataRow containing the 'Best Address' Location</param>
        /// <param name="APartnerLocationDR">DataRow containing the 'Best Address' PartnerLocation</param>
        /// <returns>False if an invalid PartnerKey was passed in or if Petra Security
        /// denied access to the Partner or if Location/PartnerLocation Data could not be loaded for the
        /// Partner, otherwise true.</returns>
        public static bool GetPartnersBestLocationData(Int64 APartnerKey,
            out TLocationPK ABestAddressPK,
            out PLocationRow ALocationDR, out PPartnerLocationRow APartnerLocationDR)
        {
            TDBTransaction ReadTransaction;
            Boolean NewTransaction;
            PPartnerLocationTable PartnerLocationDT;
            PLocationTable LocationDT;

            ALocationDR = null;
            APartnerLocationDR = null;
            ABestAddressPK = null;

            if (APartnerKey > 0)
            {
                ReadTransaction = DBAccess.GDBAccessObj.GetNewOrExistingTransaction(
                    IsolationLevel.ReadCommitted, TEnforceIsolationLevel.eilMinimum, out NewTransaction);

                try
                {
                    if (TMailing.GetPartnerLocations(APartnerKey, false,
                            true, true, true, out PartnerLocationDT))
                    {
                        TLogging.LogAtLevel(8,
                            "TMailing.GetPartnersBestLocationData: processing " + PartnerLocationDT.Rows.Count.ToString() + " Locations...");

                        if (PartnerLocationDT.Rows.Count > 1)
                        {
                            Calculations.DeterminePartnerLocationsDateStatus(PartnerLocationDT, DateTime.Today);
                            ABestAddressPK = Calculations.DetermineBestAddress(PartnerLocationDT);
                        }
                        else if (PartnerLocationDT.Rows.Count == 1)
                        {
                            ABestAddressPK = new TLocationPK(PartnerLocationDT[0].SiteKey, PartnerLocationDT[0].LocationKey);
                        }
                        else
                        {
                            return false;
                        }

//                      TLogging.LogAtLevel(8, "TMailing.GetPartnersBestLocationData: BestAddressPK: " + ABestAddressPK.SiteKey.ToString() + ", " + ABestAddressPK.LocationKey.ToString());
                        APartnerLocationDR = (PPartnerLocationRow)PartnerLocationDT.Rows.Find(
                            new object[] { APartnerKey, ABestAddressPK.SiteKey, ABestAddressPK.LocationKey });

                        LocationDT = TPPartnerAddressAggregate.LoadByPrimaryKey(
                            ABestAddressPK.SiteKey, ABestAddressPK.LocationKey, ReadTransaction);

                        if (LocationDT != null)
                        {
                            ALocationDR = LocationDT[0];
                        }
                        else
                        {
                            return false;
                        }

                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
                finally
                {
                    if (NewTransaction)
                    {
                        DBAccess.GDBAccessObj.CommitTransaction();
                        TLogging.LogAtLevel(8, "TMailing.GetPartnersBestLocationData: committed own transaction.");
                    }
                }
            }
            else
            {
                return false;
            }
        }
 /// <summary>
 /// Retrieves PartnerLocation information and the rest of the PartnerInfo data, but not the
 /// 'Head' data.
 /// </summary>
 /// <param name="APartnerKey">PartnerKey of Partner to find the PartnerInfo data for</param>
 /// <param name="ALocationKey" >Location Key of the Location that the information should be
 /// retrieved for.</param>
 /// <param name="APartnerInfoDS">Typed DataSet that contains the requested data.</param>
 /// <returns>True if Partner exists, otherwise false.</returns>
 public static bool PartnerLocationAndRestOnly(Int64 APartnerKey, TLocationPK ALocationKey,
     ref PartnerInfoTDS APartnerInfoDS)
 {
     return PartnerLocationInternal(APartnerKey, ALocationKey, ref APartnerInfoDS, true);
 }
예제 #19
0
        /// <summary>
        /// Returns the Primary Key of the Location of the 'Best Address' of a Partner.
        /// </summary>
        /// <param name="APartnerKey">PartneKey of the Partner for which the 'Best Address'
        /// should be loaded for.</param>
        /// <returns>TLocationPK(-1,-1) if an invalid PartnerKey was passed in or if Petra Security
        /// denied access to the Partner or if Location/PartnerLocation Data could not be loaded for the
        /// Partner, otherwise the Primary Key of the Location of the 'Best Address' of the Partner.</returns>
        public static TLocationPK GetPartnersBestLocation(Int64 APartnerKey)
        {
            TLocationPK ReturnValue = new TLocationPK(-1, -1);
            TLocationPK LocationPK;
            PLocationRow LocationDR;
            PPartnerLocationRow PartnerLocationDR;

            if (GetPartnersBestLocationData(APartnerKey, out LocationPK, out LocationDR,
                    out PartnerLocationDR))
            {
                ReturnValue = LocationPK;
            }

            return ReturnValue;
        }
예제 #20
0
        public static Boolean PartnerInfo(Int64 APartnerKey, TLocationPK ALocationKey,
            TPartnerInfoScopeEnum APartnerInfoScope,
            out PartnerInfoTDS APartnerInfoDS)
        {
            const string DATASET_NAME = "PartnerInfo";

            Boolean ReturnValue = false;

            APartnerInfoDS = new PartnerInfoTDS(DATASET_NAME);

            switch (APartnerInfoScope)
            {
                case TPartnerInfoScopeEnum.pisHeadOnly:

                    throw new NotImplementedException();

                case TPartnerInfoScopeEnum.pisPartnerLocationAndRestOnly:

                    if (TServerLookups_PartnerInfo.PartnerLocationAndRestOnly(APartnerKey,
                            ALocationKey, ref APartnerInfoDS))
                    {
                        ReturnValue = true;
                    }
                    else
                    {
                        ReturnValue = false;
                    }

                    break;

                case TPartnerInfoScopeEnum.pisPartnerLocationOnly:

                    if (TServerLookups_PartnerInfo.PartnerLocationOnly(APartnerKey,
                            ALocationKey, ref APartnerInfoDS))
                    {
                        ReturnValue = true;
                    }
                    else
                    {
                        ReturnValue = false;
                    }

                    break;

                case TPartnerInfoScopeEnum.pisLocationPartnerLocationAndRestOnly:

                    if (TServerLookups_PartnerInfo.LocationPartnerLocationAndRestOnly(APartnerKey,
                            ALocationKey, ref APartnerInfoDS))
                    {
                        ReturnValue = true;
                    }
                    else
                    {
                        ReturnValue = false;
                    }

                    break;

                case TPartnerInfoScopeEnum.pisLocationPartnerLocationOnly:

                    if (TServerLookups_PartnerInfo.LocationPartnerLocationOnly(APartnerKey,
                            ALocationKey, ref APartnerInfoDS))
                    {
                        ReturnValue = true;
                    }
                    else
                    {
                        ReturnValue = false;
                    }

                    break;

                case TPartnerInfoScopeEnum.pisFull:

                    if (TServerLookups_PartnerInfo.AllPartnerInfoData(APartnerKey,
                            ref APartnerInfoDS))
                    {
                        ReturnValue = true;
                    }
                    else
                    {
                        ReturnValue = false;
                    }

                    break;

                default:

                    break;
            }

            return ReturnValue;
        }
예제 #21
0
 /// <summary>
 /// Constructor which automatically loads data for the Partner.
 ///
 /// </summary>
 /// <param name="APartnerKey">PartnerKey for the Partner to instantiate this object with
 /// </param>
 /// <returns>void</returns>
 public TPartnerEditUIConnector(System.Int64 APartnerKey) : base()
 {
     FPartnerKey = APartnerKey;
     FKeyForSelectingPartnerLocation = new TLocationPK(0, 0);
 }
        /// <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;
        }
예제 #23
0
 /// <summary>
 /// Constructor which automatically loads data for the Partner.
 ///
 /// @Comment Use this overload to specify which Address should be selected when
 /// the Partner Edit screen is shown.
 ///
 /// </summary>
 /// <param name="APartnerKey">PartnerKey for the Partner to instantiate this object with</param>
 /// <param name="ASiteKey">SiteKey of the PartnerLocation record of the Partner</param>
 /// <param name="ALocationKey">LocationKey of the PartnerLocation record of the Partner
 /// </param>
 /// <returns>void</returns>
 public TPartnerEditUIConnector(Int64 APartnerKey, Int64 ASiteKey, Int32 ALocationKey) : base()
 {
     FPartnerKey = APartnerKey;
     FKeyForSelectingPartnerLocation = new TLocationPK(ASiteKey, ALocationKey);
 }
        /// <summary>
        /// Prepare the address changes. Check for the rules regarding locations
        /// </summary>
        public static TSubmitChangesResult PrepareChanges(PartnerEditTDS AInspectDS,
            Int64 APartnerKey,
            String APartnerClass,
            TDBTransaction ASubmitChangesTransaction,
            ref PartnerAddressAggregateTDS AResponseDS,
            out TVerificationResultCollection AVerificationResult)
        {
            PartnerAddressAggregateTDSSimilarLocationParametersTable ExistingLocationParametersDT;
            PartnerAddressAggregateTDSChangePromotionParametersTable ChangeLocationParametersDT;
            PartnerAddressAggregateTDSAddressAddedOrChangedPromotionTable AddressAddedOrChangedPromotionParametersDT;

            AVerificationResult = null;

            if (AInspectDS == null)
            {
//              TLogging.LogAtLevel(9, "SubmitChanges: AInspectDS = nil!");
                return TSubmitChangesResult.scrNothingToBeSaved;
            }

            AVerificationResult = new TVerificationResultCollection();
            TLocationPK[, ] SimilarLocationReUseKeyMapping = new TLocationPK[1, 2];

            if (AInspectDS.PLocation != null)
            {
//              TLogging.LogAtLevel(9, "SubmitChanges: PLocation Rows: " + AInspectDS.PLocation.Rows.Count.ToString());
            }

            if (AInspectDS.PPartnerLocation != null)
            {
//              TLogging.LogAtLevel(9, "SubmitChanges: PPartnerLocation Rows: " + AInspectDS.PPartnerLocation.Rows.Count.ToString());
            }

            if (TLogging.DL >= 8)
            {
                DebugLocationsBeforeSaving(AInspectDS);
            }

            // Check if Parameter Tables are passed in
            CheckParameterTables(AResponseDS,
                out ExistingLocationParametersDT,
                out ChangeLocationParametersDT,
                out AddressAddedOrChangedPromotionParametersDT);

            if (AInspectDS.PLocation != null)
            {
                TSubmitChangesResult result = ProcessLocationChanges(
                    AInspectDS.PLocation,
                    AInspectDS.PPartnerLocation,
                    ref AResponseDS,
                    ASubmitChangesTransaction,
                    APartnerKey,
                    ref ExistingLocationParametersDT,
                    ref SimilarLocationReUseKeyMapping,
                    ref AddressAddedOrChangedPromotionParametersDT,
                    ref ChangeLocationParametersDT,
                    ref AVerificationResult);

                if (result != TSubmitChangesResult.scrOK)
                {
                    // Stop processing here, we need more information!

                    return result;
                }
            }

            if (AInspectDS.PPartnerLocation != null)
            {
                TSubmitChangesResult result = ProcessPartnerLocationChanges(
                    AInspectDS.PPartnerLocation,
                    ref AResponseDS,
                    ASubmitChangesTransaction,
                    APartnerKey,
                    APartnerClass,
                    ref SimilarLocationReUseKeyMapping,
                    ref ExistingLocationParametersDT,
                    ref AddressAddedOrChangedPromotionParametersDT,
                    ref ChangeLocationParametersDT,
                    ref AVerificationResult);

                if (result != TSubmitChangesResult.scrOK)
                {
                    // Stop processing here, we need more information!

                    return result;
                }
            }

            /*
             * Actual saving of data
             */
            if (AInspectDS.PLocation != null)
            {
//              TLogging.LogAtLevel(9, "SubmitChanges: Length(SimilarLocationReUseKeyMapping): " + Convert.ToInt16(SimilarLocationReUseKeyMapping.GetLength(0)).ToString());

                if ((SimilarLocationReUseKeyMapping.GetLength(0) - 1) > 0)
                {
                    for (Int16 LocationReUseCounter = 1;
                         LocationReUseCounter <= SimilarLocationReUseKeyMapping.GetLength(0) - 1;
                         LocationReUseCounter += 1)
                    {
/* if DEBUGMODE
 *                      if (TLogging.DL >= 9)
 *                      {
 *                          TLogging.Log("LocationReUseCounter: " + LocationReUseCounter.ToString());
 *                          TLogging.Log(
 *                              "SubmitChanges: LocationReUseKeyMapping[" + LocationReUseCounter.ToString() +
 *                              ", 0].LocationKey: " +
 *                              SimilarLocationReUseKeyMapping[LocationReUseCounter, 0].LocationKey.ToString());
 *                          TLogging.Log(
 *                              "SubmitChanges: LocationReUseKeyMapping[" + LocationReUseCounter.ToString() +
 *                              ", 1].LocationKey: " +
 *                              SimilarLocationReUseKeyMapping[LocationReUseCounter, 1].LocationKey.ToString());
 *                      }
 */
                        PLocationRow ReUsedLocationDR =
                            (PLocationRow)AInspectDS.PLocation.Rows.Find(
                                new System.Object[] { SimilarLocationReUseKeyMapping[LocationReUseCounter, 0].SiteKey,
                                                      SimilarLocationReUseKeyMapping[LocationReUseCounter, 0].LocationKey });

                        if (ReUsedLocationDR != null)
                        {
                            // Overwrite the originally submitted Key with the one that
                            // replaces it. This is needed to have the correct Key on
                            // the Client side!
                            ReUsedLocationDR.SiteKey = SimilarLocationReUseKeyMapping[LocationReUseCounter, 1].SiteKey;
                            ReUsedLocationDR.LocationKey = SimilarLocationReUseKeyMapping[LocationReUseCounter, 1].LocationKey;

                            // Make the DataRow 'unchanged' so that it doesn't get saved in the
                            // SubmitChanges call for PLocation!
                            ReUsedLocationDR.AcceptChanges();

                            // Remember that the row should not be submitted lateron
                            // NotToBeSubmittedLocationRows.Add(ReUsedLocationDR);
                        }
                        else
                        {
                            throw new EOPAppException("ReUsedLocationDR for SiteKey " +
                                SimilarLocationReUseKeyMapping[LocationReUseCounter,
                                                               0].SiteKey.ToString() + " and LocationKey " +
                                SimilarLocationReUseKeyMapping[LocationReUseCounter, 0].LocationKey.ToString() + " could not be found!");
                        }
                    }
                }
            }

            if (AInspectDS.PPartnerLocation != null)
            {
//              TLogging.LogAtLevel(9, "SubmitChanges: Length(SimilarLocationReUseKeyMapping): " + Convert.ToInt16(SimilarLocationReUseKeyMapping.GetLength(0)).ToString());

                if ((SimilarLocationReUseKeyMapping.GetLength(0) - 1) > 0)
                {
                    for (Int16 LocationReUseCounter = 1;
                         LocationReUseCounter <= SimilarLocationReUseKeyMapping.GetLength(0) - 1;
                         LocationReUseCounter += 1)
                    {
//                      TLogging.LogAtLevel(9, "LocationReUseCounter: " + LocationReUseCounter.ToString());
//                      TLogging.LogAtLevel(9, "SubmitChanges: LocationReUseKeyMapping[" + LocationReUseCounter.ToString() + ", 0].LocationKey: " +
//                                SimilarLocationReUseKeyMapping[LocationReUseCounter, 0].LocationKey.ToString());
                        PPartnerLocationRow ReUsedPartnerLocationDR = (PPartnerLocationRow)AInspectDS.PPartnerLocation.Rows.Find(
                            new System.Object[] { APartnerKey, SimilarLocationReUseKeyMapping[LocationReUseCounter, 0].SiteKey,
                                                  SimilarLocationReUseKeyMapping[LocationReUseCounter, 0].LocationKey });

                        if (ReUsedPartnerLocationDR != null)
                        {
                            // Overwrite the originally submitted Key with the one that
                            // replaces it. This is needed to have the correct Key on
                            // the Client side!
                            ReUsedPartnerLocationDR.SiteKey = SimilarLocationReUseKeyMapping[LocationReUseCounter, 1].SiteKey;
                            ReUsedPartnerLocationDR.LocationKey = SimilarLocationReUseKeyMapping[LocationReUseCounter, 1].LocationKey;
                        }
                        else
                        {
                            throw new EOPAppException("ReUsedPartnerLocationDR for SiteKey " +
                                SimilarLocationReUseKeyMapping[LocationReUseCounter,
                                                               0].SiteKey.ToString() + " and LocationKey " +
                                SimilarLocationReUseKeyMapping[LocationReUseCounter, 0].LocationKey.ToString() + " could not be found!");
                        }
                    }
                }
            }

            return TSubmitChangesResult.scrOK;
        }
예제 #25
0
 /// <summary>
 /// Constructor for creating a new Partner.
 ///
 /// </summary>
 /// <returns>void</returns>
 public TPartnerEditUIConnector() : base()
 {
     FKeyForSelectingPartnerLocation = new TLocationPK(0, 0);
 }
        /// <summary>
        /// todoComment
        /// </summary>
        /// <param name="ARow"></param>
        /// <param name="ALocationReUseKeyMapping"></param>
        /// <returns></returns>
        private static TLocationPK DetermineReplacedLocationPK(DataRow ARow, TLocationPK[, ] ALocationReUseKeyMapping)
        {
            TLocationPK ReturnValue;
            TLocationPK SubmittedLocationPK;
            Int64 SiteKey;
            Int32 LocationKey;
            int Counter;

            ReturnValue = null;
            SubmittedLocationPK = null;

            if (!((ARow is PLocationRow) || (ARow is PPartnerLocationRow)))
            {
                throw new System.ArgumentException("ARow Argument must be either of Type PLocationRow or of Type PPartnerLocationRow");
            }

            if (ARow is PLocationRow)
            {
                SiteKey = ((PLocationRow)ARow).SiteKey;
                LocationKey = (int)((PLocationRow)ARow).LocationKey;
            }
            else
            {
                SiteKey = ((PPartnerLocationRow)ARow).SiteKey;
                LocationKey = ((PPartnerLocationRow)ARow).LocationKey;
            }

            // Check if passed in Key can be found in the KeyMapping Array
            if ((ALocationReUseKeyMapping.GetLength(0) - 1) > 0)
            {
//              TLogging.LogAtLevel(9, "(Length(ALocationReUseKeyMapping): " + Convert.ToInt16(ALocationReUseKeyMapping.GetLength(0)).ToString());
                for (Counter = 1; Counter <= ALocationReUseKeyMapping.GetLength(0) - 1; Counter += 1)
                {
                    SubmittedLocationPK = ALocationReUseKeyMapping[Counter, 0];

                    if ((SubmittedLocationPK.LocationKey == LocationKey) && (SubmittedLocationPK.SiteKey == SiteKey))
                    {
                        // found passed in Key in the KeyMapping Array
                        ReturnValue = ALocationReUseKeyMapping[Counter, 1];
//                      TLogging.LogAtLevel(9, "DetermineReplacedLocationPK: Key found in Key Mapping.");
                        continue;
                    }
                }
            }

            if (ReturnValue == null)
            {
                // passed in Key not found in the KeyMapping Array
//              TLogging.LogAtLevel(9, "DetermineReplacedLocationPK: Key *not* found in Key Mapping");
                ReturnValue = new TLocationPK(SiteKey, LocationKey);
            }

//          TLogging.LogAtLevel(9, "DetermineReplacedLocationPK: ReturnValue.SiteKey: " + ReturnValue.SiteKey.ToString() + "; ReturnValue.LocationKey: " + ReturnValue.LocationKey.ToString());
            return ReturnValue;
        }
예제 #27
0
        private void LoadData(Boolean ADelayedDataLoading, TPartnerEditTabPageEnum ATabPage)
        {
            PartnerEditTDSMiscellaneousDataTable MiscellaneousDataDT;
            PartnerEditTDSMiscellaneousDataRow MiscellaneousDataDR;
            TDBTransaction ReadTransaction;
            DateTime LastGiftDate;
            DateTime LastContactDate;
            String LastGiftInfo;
            TLocationPK LocationPK;
            Boolean OfficeSpecificDataLabelsAvailable = false;
            Int32 ItemsCountAddresses = 0;
            Int32 ItemsCountAddressesActive = 0;
            Int32 ItemsCountContactDetails = -1;
            Int32 ItemsCountContactDetailsActive = -1;
            Int32 ItemsCountSubscriptions = 0;
            Int32 ItemsCountSubscriptionsActive = 0;
            Int32 ItemsCountPartnerTypes = 0;
            Int32 ItemsCountPartnerRelationships = 0;
            Int32 ItemsCountFamilyMembers = 0;
            Int32 ItemsCountPartnerInterests = 0;
            Int32 ItemsCountInterests = 0;
            Int32 ItemsCountPartnerBankingDetails = 0;
            Int32 ItemsCountContacts = 0;
            Int64 FoundationOwner1Key = 0;
            Int64 FoundationOwner2Key = 0;
            bool HasEXWORKERPartnerType = false;

//          TLogging.LogAtLevel(7, "TPartnerEditUIConnector.LoadData called. ADelayedDataLoading: " + ADelayedDataLoading.ToString() + "; ATabPage: " +
//               Enum.GetName(typeof(TPartnerEditTabPageEnum), ATabPage));

            // create the FPartnerEditScreenDS DataSet that will later be passed to the Client
            FPartnerEditScreenDS = new PartnerEditTDS(DATASETNAME);

            try
            {
                ReadTransaction = DBAccess.GDBAccessObj.BeginTransaction(IsolationLevel.RepeatableRead, 5);
                try
                {
                    #region Load data using the DataStore

                    // Partner
                    PPartnerAccess.LoadByPrimaryKey(FPartnerEditScreenDS, FPartnerKey, ReadTransaction);

                    if (FPartnerEditScreenDS.PPartner.Rows.Count != 0)
                    {
                        FPartnerClass = SharedTypes.PartnerClassStringToEnum(FPartnerEditScreenDS.PPartner[0].PartnerClass);
                    }
                    else
                    {
                        throw new EPartnerNotExistantException();
                    }

                    /*
                     * For Partners that aren't ORGANISATIONs we can check access to the Partner here.
                     * For Partners that *are* ORGANISATIONS we need to do a more elaborate check
                     * further down the code of this Method!
                     */
                    if (FPartnerClass != TPartnerClass.ORGANISATION)
                    {
                        /*
                         * Check if access to Partner is granted; if not, an
                         * ESecurityPartnerAccessDeniedException will be thrown by the called Method!
                         */
                        Ict.Petra.Shared.MPartner.TSecurity.CanAccessPartnerExc(FPartnerEditScreenDS.PPartner[0], false, null);
                    }

                    // Partner Types
                    FPartnerEditScreenDS.Merge(GetPartnerTypesInternal(out ItemsCountPartnerTypes, false));

                    if ((ADelayedDataLoading) && (ATabPage != TPartnerEditTabPageEnum.petpPartnerTypes))
                    {
                        // Empty Tables again, we don't want to transfer the data contained in them
                        FPartnerEditScreenDS.PPartnerType.Rows.Clear();
                    }

                    // Subscriptions
                    FPartnerEditScreenDS.Merge(GetSubscriptionsInternal(out ItemsCountSubscriptions, false));

                    if ((ADelayedDataLoading) && (ATabPage != TPartnerEditTabPageEnum.petpSubscriptions))
                    {
                        // Only count Subscriptions
                        Calculations.CalculateTabCountsSubscriptions(FPartnerEditScreenDS.PSubscription,
                            out ItemsCountSubscriptions,
                            out ItemsCountSubscriptionsActive);

                        // Empty Tables again, we don't want to transfer the data contained in them
                        FPartnerEditScreenDS.PSubscription.Rows.Clear();
                    }

                    // Partner Attributes - those always need to get loaded!
                    FPartnerEditScreenDS.Merge(PPartnerAttributeAccess.LoadViaPPartner(FPartnerKey, ReadTransaction));

                    // Contact Details
                    GetPartnerContactDetailsInternal(out ItemsCountContactDetails);

                    if ((ADelayedDataLoading) && (ATabPage != TPartnerEditTabPageEnum.petpContactDetails))
                    {
                        // Count Contact Details
                        Calculations.CalculateTabCountsPartnerContactDetails(FPartnerEditScreenDS.PPartnerAttribute,
                            out ItemsCountContactDetails, out ItemsCountContactDetailsActive);
                    }

                    // Partner Relationships
                    FPartnerEditScreenDS.Merge(GetPartnerRelationshipsInternal(out ItemsCountPartnerRelationships, false));

                    if ((ADelayedDataLoading) && (ATabPage != TPartnerEditTabPageEnum.petpPartnerRelationships))
                    {
                        // Only count Relationships
                        Calculations.CalculateTabCountsPartnerRelationships(FPartnerEditScreenDS.PPartnerRelationship,
                            out ItemsCountPartnerRelationships);

                        // Empty Tables again, we don't want to transfer the data contained in them
                        FPartnerEditScreenDS.PPartnerRelationship.Rows.Clear();
                    }

                    // Locations and PartnerLocations
                    TLogging.LogAtLevel(9, "TPartnerEditUIConnector.LoadData: Before TPPartnerAddressAggregate.LoadAll");
                    TPPartnerAddressAggregate.LoadAll(FPartnerEditScreenDS, FPartnerKey, ReadTransaction);

                    if (FKeyForSelectingPartnerLocation.LocationKey > 0)
                    {
                        if (FPartnerEditScreenDS.PPartnerLocation.Rows.Find(new Object[] { FPartnerKey, FKeyForSelectingPartnerLocation.SiteKey,
                                                                                           FKeyForSelectingPartnerLocation.LocationKey }) == null)
                        {
                            throw new EPartnerLocationNotExistantException(
                                "PartnerLocation SiteKey " + FKeyForSelectingPartnerLocation.SiteKey.ToString() + " and LocationKey " +
                                FKeyForSelectingPartnerLocation.LocationKey.ToString());
                        }
                    }

                    if (((!ADelayedDataLoading)) || (ATabPage == TPartnerEditTabPageEnum.petpAddresses))
                    {
                        // Determination of the address list icons and the 'best' address (these calls change certain columns in some rows!)
                        Calculations.DeterminePartnerLocationsDateStatus((DataSet)FPartnerEditScreenDS);
                        LocationPK = Calculations.DetermineBestAddress((DataSet)FPartnerEditScreenDS);
                    }
                    else
                    {
                        // Only count
                        Calculations.CalculateTabCountsAddresses(FPartnerEditScreenDS.PPartnerLocation,
                            out ItemsCountAddresses,
                            out ItemsCountAddressesActive);

                        // Empty Tables again, we don't want to transfer the data contained in them
                        FPartnerEditScreenDS.PLocation.Rows.Clear();
                        FPartnerEditScreenDS.PPartnerLocation.Rows.Clear();

                        // location will be determined correctly on the Client side...
                        LocationPK = new TLocationPK(0, 0);
                    }

                    // PartnerInterests
                    if (((!ADelayedDataLoading)) || (ATabPage == TPartnerEditTabPageEnum.petpInterests))
                    {
                        DataRow InterestRow;

                        // Load data for Interests
                        FPartnerEditScreenDS.Merge(GetPartnerInterestsInternal(out ItemsCountPartnerInterests, false));
                        FPartnerEditScreenDS.Merge(GetInterestsInternal(out ItemsCountInterests, false));

                        // fill field for interest category in PartnerInterest table in dataset
                        foreach (PartnerEditTDSPPartnerInterestRow row in FPartnerEditScreenDS.PPartnerInterest.Rows)
                        {
                            InterestRow = FPartnerEditScreenDS.PInterest.Rows.Find(new object[] { row.Interest });

                            if (InterestRow != null)
                            {
                                row.InterestCategory = ((PInterestRow)InterestRow).Category;
                            }
                        }
                    }
                    else
                    {
                        // Only count Interests
                        GetPartnerInterestsInternal(out ItemsCountPartnerInterests, true);
                    }

                    #region Partner Details data according to PartnerClass

                    switch (FPartnerClass)
                    {
                        case TPartnerClass.PERSON:

                            // Disable some constraints that relate to other tables in the DataSet that are not filled with data.
                            // This applies for the DataTables that exist for a certain Partner Class, eg. Person, where all other
                            // DataTables that represent certain Partner Classes are not filled.
                            FPartnerEditScreenDS.DisableConstraint("FKPerson2");

                            // points to PFamily
                            FPartnerEditScreenDS.DisableConstraint("FKPerson4");

                            // points to PUnit
                            TLogging.LogAtLevel(9, "Disabled Constraints in Typed DataSet PartnerEditTDS.");
                            PPersonAccess.LoadByPrimaryKey(FPartnerEditScreenDS, FPartnerKey, ReadTransaction);

                            // Gift Destination
                            PPartnerGiftDestinationAccess.LoadViaPPartner(FPartnerEditScreenDS,
                            FPartnerEditScreenDS.PPerson[0].FamilyKey,
                            ReadTransaction);

                            // Determine whether the Partner has a 'EX-WORKER*' Partner Type
                            HasEXWORKERPartnerType = Ict.Petra.Shared.MPartner.Checks.PartnerIsExWorker(FPartnerEditScreenDS.PPartnerGiftDestination);

                            if (((!ADelayedDataLoading)) || (ATabPage == TPartnerEditTabPageEnum.petpFamilyMembers))
                            {
                                // Load data for Family Members
                                FPartnerEditScreenDS.Merge(GetFamilyMembersInternal(FPartnerEditScreenDS.PPerson[0].FamilyKey, "",
                                        out ItemsCountFamilyMembers, false));
                            }
                            else
                            {
                                // Only count Family Members
                                GetFamilyMembersInternal(FPartnerEditScreenDS.PPerson[0].FamilyKey, "", out ItemsCountFamilyMembers, true);
                            }

                            break;

                        case TPartnerClass.FAMILY:
                            PFamilyAccess.LoadByPrimaryKey(FPartnerEditScreenDS, FPartnerKey, ReadTransaction);

                            // Gift Destination
                            PPartnerGiftDestinationAccess.LoadViaPPartner(FPartnerEditScreenDS, FPartnerKey, ReadTransaction);

                            // Determine whether the Partner has a 'EX-WORKER*' Partner Type
                            HasEXWORKERPartnerType = Ict.Petra.Shared.MPartner.Checks.PartnerIsExWorker(FPartnerEditScreenDS.PPartnerGiftDestination);

                            if (((!ADelayedDataLoading)) || (ATabPage == TPartnerEditTabPageEnum.petpFamilyMembers))
                            {
                                // Load data for Family Members
                                FPartnerEditScreenDS.Merge(GetFamilyMembersInternal(FPartnerEditScreenDS.PFamily[0].PartnerKey, "",
                                        out ItemsCountFamilyMembers, false));
                            }
                            else
                            {
                                // Only count Family Members
                                GetFamilyMembersInternal(FPartnerEditScreenDS.PFamily[0].PartnerKey, "", out ItemsCountFamilyMembers, true);
                            }

                            break;

                        case TPartnerClass.CHURCH:
                            PChurchAccess.LoadByPrimaryKey(FPartnerEditScreenDS, FPartnerKey, ReadTransaction);
                            break;

                        case TPartnerClass.ORGANISATION:
                            POrganisationAccess.LoadByPrimaryKey(FPartnerEditScreenDS, FPartnerKey, ReadTransaction);

                            if (FPartnerEditScreenDS.POrganisation[0].Foundation)
                            {
                                if (!((UserInfo.GUserInfo.IsInModule(SharedConstants.PETRAMODULE_DEVUSER))
                                      || (UserInfo.GUserInfo.IsInModule(SharedConstants.PETRAMODULE_DEVADMIN))))
                                {
                                    throw new ESecurityScreenAccessDeniedException(
                                        // Some users won't have access to edit partners that are foundations. Foundations are a special type of organisation.
                                        // They usually are important donors, and they should not be approached by any user in the
                                        // office, but only by the person that has been assigned to do that job
                                        Catalog.GetString(
                                            "You do not have access to Partners of Partner Class 'ORGANISATION' that are 'Foundations'!"));
                                }
                                else
                                {
                                    // User has access to open the screen, based on Module Security
                                    if (((!ADelayedDataLoading)) || (ATabPage == TPartnerEditTabPageEnum.petpFoundationDetails))
                                    {
                                        // Load all data that there is for a Foundation (across several DataTables)
                                        FPartnerEditScreenDS.Merge(GetDataFoundation(false));
                                    }
                                    else
                                    {
                                        // Load just p_foundation record (needed for security, see below)
                                        FPartnerEditScreenDS.Merge(GetDataFoundation(true));
                                    }

                                    if (FPartnerEditScreenDS.PFoundation.Rows.Count != 0)
                                    {
                                        // Store Foundation Owner1 and Foundation Owner2 from the
                                        // p_foundation record. This information will be evaluated in the
                                        // Partner Edit screen to allow/disallow access to the Foundation
                                        // Details Tab.
                                        if (FPartnerEditScreenDS.PFoundation[0].IsOwner1KeyNull())
                                        {
                                            FoundationOwner1Key = 0;
                                        }
                                        else
                                        {
                                            FoundationOwner1Key = FPartnerEditScreenDS.PFoundation[0].Owner1Key;
                                        }

                                        if (FPartnerEditScreenDS.PFoundation[0].IsOwner2KeyNull())
                                        {
                                            FoundationOwner2Key = 0;
                                        }
                                        else
                                        {
                                            FoundationOwner2Key = FPartnerEditScreenDS.PFoundation[0].Owner2Key;
                                        }

                                        if ((ADelayedDataLoading) && (ATabPage != TPartnerEditTabPageEnum.petpFoundationDetails))
                                        {
                                            // We don't want to transfer the data of the table until it is
                                            // needed on the Client side (also for security reasons).
                                            FPartnerEditScreenDS.Tables.Remove(FPartnerEditScreenDS.PFoundation);
                                        }

                                        /*
                                         * Check if access to Partner is granted; if not, an
                                         * ESecurityPartnerAccessDeniedException will be thrown by the called Method!
                                         */
                                        Ict.Petra.Shared.MPartner.TSecurity.CanAccessPartnerExc(
                                            FPartnerEditScreenDS.PPartner[0], true,
                                            FPartnerEditScreenDS.PFoundation[0]);
                                    }
                                    else
                                    {
                                        // Althought the Organisation is marked to be a Foundation, no
                                        // p_foundation record exists. This should of course not happen,
                                        // but in case it does: mark the Organisation to be NO Foundation.
                                        FPartnerEditScreenDS.POrganisation[0].Foundation = false;

                                        /*
                                         * Check if access to Partner is granted; if not, an
                                         * ESecurityPartnerAccessDeniedException will be thrown by the called Method!
                                         */
                                        Ict.Petra.Shared.MPartner.TSecurity.CanAccessPartnerExc(
                                            FPartnerEditScreenDS.PPartner[0], false, null);
                                    }
                                }
                            }
                            else
                            {
                                /*
                                 * Check if access to Partner is granted; if not, an
                                 * ESecurityPartnerAccessDeniedException will be thrown by the called Method!
                                 */
                                Ict.Petra.Shared.MPartner.TSecurity.CanAccessPartnerExc(FPartnerEditScreenDS.PPartner[0], false, null);
                            }

                            break;

                        case TPartnerClass.BANK:

                            // Get the main information about a BANK partner
                            PBankAccess.LoadByPrimaryKey(FPartnerEditScreenDS, FPartnerKey, ReadTransaction);

                            // Gain information about the BANK partner's banking details
                            // When dealing with this grid one has to consider that the Netherland do not
                            // know bank branches and that Credit Cards do not have branches as well.
                            // Last time I checked how many accounts one bank in the Netherlands had
                            // I ended up with some 9756. I was also puzzled what use this grid may have.
                            // It is very tedious to find the right bank account from some 9000 bank
                            // accounts. Therefore the paged grid would be needed. But Rob decided that
                            // we currently do not build this grid into this screen, since this sreen
                            // was hardly used anyway. We are happy to wait for the first complaints.
                            //
                            // FPartnerEditScreenDS := GetBankingDetailsInternal(ReadTransaction, FPartnerKey);
                            break;

                        case TPartnerClass.UNIT:
                            PUnitAccess.LoadByPrimaryKey(FPartnerEditScreenDS, FPartnerKey, ReadTransaction);
                            UmUnitStructureAccess.LoadViaPUnitChildUnitKey(FPartnerEditScreenDS, FPartnerKey, ReadTransaction);
                            break;

                        case TPartnerClass.VENUE:
                            PVenueAccess.LoadByPrimaryKey(FPartnerEditScreenDS, FPartnerKey, ReadTransaction);
                            break;
                    }

                    #endregion

                    // financial details
                    if ((!ADelayedDataLoading) || (ATabPage == TPartnerEditTabPageEnum.petpFinanceDetails))
                    {
                        FPartnerEditScreenDS.Merge(GetBankingDetails());
                    }

                    ItemsCountPartnerBankingDetails = PPartnerBankingDetailsAccess.CountViaPPartner(FPartnerKey, ReadTransaction);

                    // Office Specific Data
                    if ((!ADelayedDataLoading) || (ATabPage == TPartnerEditTabPageEnum.petpOfficeSpecific))
                    {
                        FPartnerEditScreenDS.Merge(GetDataLocalPartnerDataValuesInternal(out OfficeSpecificDataLabelsAvailable, false));
                    }
                    else
                    {
                        FPartnerEditScreenDS.Merge(GetDataLocalPartnerDataValuesInternal(out OfficeSpecificDataLabelsAvailable, true));
                    }

                    // Console.WriteLine('FPartnerEditScreenDS.PDataLabelValuePartner.Rows.Count: ' + FPartnerEditScreenDS.PDataLabelValuePartner.Rows.Count.ToString);

                    #region Individual Data (Personnel Tab)

                    if (((!ADelayedDataLoading)) || (ATabPage == TPartnerEditTabPageEnum.petpPersonnelIndividualData))
                    {
                        FPartnerEditScreenDS.Merge(TIndividualDataWebConnector.GetData(FPartnerKey, TIndividualDataItemEnum.idiSummary));
//                      Console.WriteLine("FPartnerEditScreenDS.PDataLabelValuePartner.Rows.Count: " + FPartnerEditScreenDS.Tables["SummaryData"].Rows.Count.ToString());
                    }

                    #endregion

                    #endregion

                    #region Process data

                    // Determination of Last Gift information
                    TGift.GetLastGiftDetails(FPartnerKey, out LastGiftDate, out LastGiftInfo);

                    // Determination of Last Contact Date
                    TMailroom.GetLastContactDate(FPartnerKey, out LastContactDate);
                    GetContactsInternal(out ItemsCountContacts, out LastContactDate);

                    // Create 'miscellaneous' DataRow
                    MiscellaneousDataDT = FPartnerEditScreenDS.MiscellaneousData;
                    MiscellaneousDataDR = MiscellaneousDataDT.NewRowTyped(false);
                    MiscellaneousDataDR.PartnerKey = FPartnerKey;

                    if (FKeyForSelectingPartnerLocation.LocationKey == 0)
                    {
                        MiscellaneousDataDR.SelectedSiteKey = LocationPK.SiteKey;
                        MiscellaneousDataDR.SelectedLocationKey = LocationPK.LocationKey;
                    }
                    else
                    {
//                      TLogging.LogAtLevel(6, "Passed in FKeyForSelectingPartnerLocation.SiteKey and FKeyForSelectingPartnerLocation.LocationKey: " +
//                          FKeyForSelectingPartnerLocation.SiteKey.ToString() + "/" + FKeyForSelectingPartnerLocation.LocationKey.ToString());

                        MiscellaneousDataDR.SelectedSiteKey = FKeyForSelectingPartnerLocation.SiteKey;
                        MiscellaneousDataDR.SelectedLocationKey = FKeyForSelectingPartnerLocation.LocationKey;
                    }

                    if (LastGiftDate != DateTime.MinValue)
                    {
                        MiscellaneousDataDR.LastGiftDate = LastGiftDate;
                    }
                    else
                    {
                        MiscellaneousDataDR.SetLastGiftDateNull();
                    }

                    if (LastContactDate != DateTime.MinValue)
                    {
                        MiscellaneousDataDR.LastContactDate = LastContactDate;
                    }
                    else
                    {
                        MiscellaneousDataDR.SetLastContactDateNull();
                    }

                    MiscellaneousDataDR.LastGiftInfo = LastGiftInfo;
                    MiscellaneousDataDR.ItemsCountAddresses = ItemsCountAddresses;
                    MiscellaneousDataDR.ItemsCountAddressesActive = ItemsCountAddressesActive;
                    MiscellaneousDataDR.ItemsCountContactDetails = ItemsCountContactDetails;
                    MiscellaneousDataDR.ItemsCountContactDetailsActive = ItemsCountContactDetailsActive;
                    MiscellaneousDataDR.ItemsCountSubscriptions = ItemsCountSubscriptions;
                    MiscellaneousDataDR.ItemsCountSubscriptionsActive = ItemsCountSubscriptionsActive;
                    MiscellaneousDataDR.ItemsCountContacts = ItemsCountContacts;
                    MiscellaneousDataDR.ItemsCountPartnerTypes = ItemsCountPartnerTypes;
                    MiscellaneousDataDR.ItemsCountPartnerRelationships = ItemsCountPartnerRelationships;
                    MiscellaneousDataDR.ItemsCountFamilyMembers = ItemsCountFamilyMembers;
                    MiscellaneousDataDR.ItemsCountInterests = ItemsCountPartnerInterests;
                    MiscellaneousDataDR.ItemsCountPartnerBankingDetails = ItemsCountPartnerBankingDetails;
                    MiscellaneousDataDR.OfficeSpecificDataLabelsAvailable = OfficeSpecificDataLabelsAvailable;
                    MiscellaneousDataDR.FoundationOwner1Key = FoundationOwner1Key;
                    MiscellaneousDataDR.FoundationOwner2Key = FoundationOwner2Key;
                    MiscellaneousDataDR.HasEXWORKERPartnerType = HasEXWORKERPartnerType;
                    MiscellaneousDataDT.Rows.Add(MiscellaneousDataDR);
                    #endregion

                    // Add this partner key to the list of recently used partners.
                    TRecentPartnersHandling.AddRecentlyUsedPartner(FPartnerKey, FPartnerClass, false, TLastPartnerUse.lpuMailroomPartner);
                }
                catch (EPartnerLocationNotExistantException)
                {
                    // don't log this exception  this is thrown on purpose here and the Client deals with it.
                    DBAccess.GDBAccessObj.RollbackTransaction();
                    throw;
                }
                catch (ESecurityPartnerAccessDeniedException)
                {
                    // don't log this exception  this is thrown on purpose here and the Client deals with it.
                    DBAccess.GDBAccessObj.RollbackTransaction();
                    throw;
                }
                catch (Exception Exp)
                {
                    DBAccess.GDBAccessObj.RollbackTransaction();
                    TLogging.Log("TPartnerEditUIConnector.LoadData exception: " + Exp.ToString(), TLoggingType.ToLogfile);
                    TLogging.Log(Exp.StackTrace, TLoggingType.ToLogfile);
                    throw;
                }
            }
            finally
            {
                if (DBAccess.GDBAccessObj.Transaction != null)
                {
                    DBAccess.GDBAccessObj.CommitTransaction();
                }
            }

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

            // Remove all Tables that were not filled with data before remoting them.
            // Examples for such DataTables are the ones that exist for a certain Partner
            // Class, eg. Person  only one of those Tables will be filled, the other ones
            // are not needed at the Client side.
            FPartnerEditScreenDS.RemoveEmptyTables();
        }
        /// <summary>
        /// Allows adding of a new Location of a FAMILY Partner to all PERSONS of that
        /// FAMILY.
        ///
        /// @comment Must only be called for Partners of Partner Class FAMILY - the
        /// function does no checks on that and will fail for other Partner Classes!
        /// </summary>
        /// <returns>void</returns>
        private static TSubmitChangesResult PerformLocationFamilyMemberPropagationChecks(PPartnerLocationRow APartnerLocationRow,
            ref PartnerAddressAggregateTDS AResponseDS,
            TDBTransaction ASubmitChangesTransaction,
            Int64 APartnerKey,
            String APartnerClass,
            ref PartnerAddressAggregateTDSAddressAddedOrChangedPromotionTable AAddressAddedPromotionDT,
            ref PPartnerLocationTable APartnerLocationTable,
            PartnerAddressAggregateTDSSimilarLocationParametersTable AExistingLocationParametersDT,
            TLocationPK[, ] ALocationReUseKeyMapping,
            out Boolean APerformPropagation,
            ref TVerificationResultCollection AVerificationResult)
        {
//          TLogging.LogAtLevel(9, "PerformLocationFamilyMemberPropagationChecks for LocationKey: " + APartnerLocationRow.LocationKey.ToString() +
//                    "; AAddressAddedPromotionDT.Rows.Count: " + AAddressAddedPromotionDT.Rows.Count.ToString());

            APerformPropagation = false;
            TLocationPK SubmittedLocationPK = DetermineReplacedLocationPK(APartnerLocationRow, ALocationReUseKeyMapping);
            TLocationPK LocationPK = DetermineReplacedLocationPK(APartnerLocationRow, AExistingLocationParametersDT);

            if (CheckFamilyMemberPropagation(APartnerLocationRow, APartnerKey, APartnerClass, ref AAddressAddedPromotionDT, LocationPK,
                    ASubmitChangesTransaction))
            {
                // Check if there is a Parameter Row for the LocationKey we are looking at
                DataView PropagateLocationParametersDV = new DataView(AAddressAddedPromotionDT,
                    PartnerAddressAggregateTDSAddressAddedOrChangedPromotionTable.GetSiteKeyDBName() + " = " + LocationPK.SiteKey.ToString() +
                    " AND " +
                    PartnerAddressAggregateTDSAddressAddedOrChangedPromotionTable.GetLocationKeyDBName() + " = " +
                    LocationPK.LocationKey.ToString() +
                    " AND " + PartnerAddressAggregateTDSAddressAddedOrChangedPromotionTable.GetLocationAddedDBName() + " = true AND " +
                    PartnerAddressAggregateTDSAddressAddedOrChangedPromotionTable.GetAnswerProcessedClientSideDBName() + " = false",
                    "",
                    DataViewRowState.CurrentRows);

                if (PropagateLocationParametersDV.Count > 0)
                {
//                  TLogging.LogAtLevel(9, "PerformLocationFamilyMemberPropagationChecks: Location " + APartnerLocationRow.LocationKey.ToString() + ": found Family Members, 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, "PerformLocationFamilyMemberPropagationChecks: Creating AResponseDS.");
                        AResponseDS = new PartnerAddressAggregateTDS(MPartnerConstants.PARTNERADDRESSAGGREGATERESPONSE_DATASET);
                    }

//                  TLogging.LogAtLevel(9, "PerformLocationFamilyMemberPropagationChecks: AAddressAddedPromotionDT.Rows.Count: " + AAddressAddedPromotionDT.Rows.Count.ToString());
                    AResponseDS.Merge(AAddressAddedPromotionDT);
//                  TLogging.LogAtLevel(9, "PerformLocationFamilyMemberPropagationChecks: Merged AAddressAddedPromotionDT into AResponseDS.");
//                  TLogging.LogAtLevel(9, "PerformLocationFamilyMemberPropagationChecks: PerformLocationFamilyMemberPropagationChecks: AResponseDS.Tables[" +
//                            MPartnerConstants.ADDRESSADDEDORCHANGEDPROMOTION_TABLENAME + "].Rows.Count: " +
//                            AResponseDS.Tables[MPartnerConstants.EXISTINGLOCATIONPARAMETERS_TABLENAME].Rows.Count.ToString());
                    return TSubmitChangesResult.scrInfoNeeded;
                }
                else
                {
//                  TLogging.LogAtLevel(9, "PerformLocationFamilyMemberPropagationChecks: Location " + APartnerLocationRow.LocationKey.ToString() + ": found Family Members and new Location should be propagated to them!");

                    /*
                     * Family Members were found and the new Location should be added to all
                     * of them!
                     */
                    APerformPropagation = true;

                    // Load all Persons of the Family
                    PPersonTable FamilyPersonsDT = PPersonAccess.LoadViaPFamily(APartnerKey, ASubmitChangesTransaction);

                    // Find PPartnerLocation row of the Family that we should process
                    PPartnerLocationRow FamilyPartnerLocationRow = (PPartnerLocationRow)APartnerLocationTable.Rows.Find(
                        new System.Object[] { APartnerKey, APartnerLocationRow.SiteKey,
                                              APartnerLocationRow.LocationKey });

                    if (FamilyPartnerLocationRow != null)
                    {
                        for (int Counter = 0; Counter <= FamilyPersonsDT.Rows.Count - 1; Counter += 1)
                        {
                            PPersonRow ProcessedPersonRow = FamilyPersonsDT[Counter];
//                          TLogging.LogAtLevel(9,  "PerformLocationFamilyMemberPropagationChecks: Person  " + ProcessedPersonRow.PartnerKey.ToString() + ": checking...");

                            // Check if Person doesn't already have the Location
                            if (!PPartnerLocationAccess.Exists(ProcessedPersonRow.PartnerKey, SubmittedLocationPK.SiteKey,
                                    SubmittedLocationPK.LocationKey, ASubmitChangesTransaction))
                            {
                                /*
                                 * PartnerLocation records for family members are added to APartnerLocationTable for easier data handling and
                                 * will be removed again after SubmitChanges of whole dataset but before returning to client as otherwise
                                 * they would confusingly show up on client side.
                                 */

                                // Make sure record is not added more than once to APartnerLocationTable (in case it is not yet in database).
                                if (APartnerLocationTable.Rows.Find(new System.Object[] { ProcessedPersonRow.PartnerKey, SubmittedLocationPK.SiteKey,
                                                                                          SubmittedLocationPK.LocationKey }) == null)
                                {
                                    //                              TLogging.LogAtLevel(9, "PerformLocationFamilyMemberPropagationChecks: Person  " + ProcessedPersonRow.PartnerKey.ToString() +
                                    //                                  ": adding Location " + SubmittedLocationPK.LocationKey.ToString() + "...");

                                    // Add a copy of the PartnerLocation data to the Person
                                    PPartnerLocationRow AddPartnerLocationRow = APartnerLocationTable.NewRowTyped(false);
                                    AddPartnerLocationRow.ItemArray = DataUtilities.DestinationSaveItemArray(AddPartnerLocationRow,
                                        FamilyPartnerLocationRow);
                                    AddPartnerLocationRow.PartnerKey = ProcessedPersonRow.PartnerKey;
                                    AddPartnerLocationRow.SiteKey = SubmittedLocationPK.SiteKey;
                                    AddPartnerLocationRow.LocationKey = SubmittedLocationPK.LocationKey;
                                    APartnerLocationTable.Rows.Add(AddPartnerLocationRow);

                                    /*
                                     * If this Person has an PartnerLocation with LocationKey 0 (this
                                     * means that this was the only PartnerLocation so far), delete the
                                     * PartnerLocation with LocationKey 0.
                                     */
                                    if (PPartnerLocationAccess.Exists(ProcessedPersonRow.PartnerKey, SubmittedLocationPK.SiteKey, 0,
                                            ASubmitChangesTransaction))
                                    {
                                        //                                  TLogging.LogAtLevel(9, "PerformLocationFamilyMemberPropagationChecks: Person  " + ProcessedPersonRow.PartnerKey.ToString() + ": had Location 0 assigned, deleting it.");
                                        PPartnerLocationAccess.DeleteByPrimaryKey(ProcessedPersonRow.PartnerKey,
                                            APartnerLocationRow.SiteKey,
                                            0,
                                            ASubmitChangesTransaction);
                                    }
                                }
                            }
                            else
                            {
//                              TLogging.LogAtLevel(9, "PerformLocationFamilyMemberPropagationChecks: Person  " + ProcessedPersonRow.PartnerKey.ToString() +
//                                      ": already has Location " + SubmittedLocationPK.LocationKey.ToString() + " assigned.");
                            }
                        }
                    }
                    else
                    {
                        throw new EOPAppException(
                            "TPPartnerAddressAggregate.PerformLocationFamilyMemberPropagationChecks: PPartnerLocation record for Family is missing");
                    }
                }
            }
            else
            {
//              TLogging.LogAtLevel(9, "PerformLocationFamilyMemberPropagationChecks: Location " + SubmittedLocationPK.LocationKey.ToString() +
//                  ": Family either has no Family Members, or no propagation of the new Location is wanted. New Location will therefore only be added to the FAMILY.");

                /*
                 * Family either has no Family Members, or it has Members, but the decision
                 * was made that the new PartnerLocation should not be added to the Family
                 * Members.
                 * The new Location will therefore only be added to the FAMILY.
                 */
            }

            return TSubmitChangesResult.scrOK;
        }
        /// <summary>
        /// Retrieves Location and PartnerLocation information and the rest of the PartnerInfo data,
        /// but not the 'Head' data.
        /// </summary>
        /// <param name="APartnerKey">PartnerKey of Partner to find the short name for</param>
        /// <param name="ALocationKey">Location Key of the Location that the information should be
        /// retrieved for.</param>
        /// <param name="APartnerInfoDS">Typed DataSet that contains the requested data.</param>
        /// <param name="AIncludeRest">Include 'Rest' data as well</param>
        private static bool LocationPartnerLocationInternal(Int64 APartnerKey, TLocationPK ALocationKey,
            ref PartnerInfoTDS APartnerInfoDS,
            bool AIncludeRest)
        {
            bool ReturnValue = false;
            TDBTransaction ReadTransaction;
            Boolean NewTransaction = false;
            PPartnerRow PartnerDR;
            PLocationTable LocationDT;
            PPartnerLocationTable PartnerLocationDT;


            ReadTransaction = DBAccess.GDBAccessObj.GetNewOrExistingTransaction(IsolationLevel.ReadCommitted,
                TEnforceIsolationLevel.eilMinimum,
                out NewTransaction);

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

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

                    /*
                     * Load Partner Location data and rest of data first
                     */
                    PartnerLocationInternal(APartnerKey, ALocationKey, ReadTransaction, ref APartnerInfoDS);

                    /*
                     * Load Location Information; this gets merged into the already retrieved
                     * information in APartnerInfoDS (eg. Partner Location data and rest of data)
                     */
                    APartnerInfoDS.Merge(TPPartnerAddressAggregate.LoadByPrimaryKey(
                            ALocationKey.SiteKey, ALocationKey.LocationKey, ReadTransaction));

                    // Apply Address Security
                    LocationDT = APartnerInfoDS.PLocation;
                    PartnerLocationDT = APartnerInfoDS.PPartnerLocation;
                    TPPartnerAddressAggregate.ApplySecurity(ref PartnerLocationDT,
                        ref LocationDT);

                    if (AIncludeRest)
                    {
                        RestInternal(PartnerDR, ReadTransaction, ref APartnerInfoDS);
                    }

                    ReturnValue = true;
                }
            }
            catch (ESecurityPartnerAccessDeniedException)
            {
                // don't log this Exception - this is thrown on purpose here and the Client knows how to deal with it.
                throw;
            }
            catch (EDBAccessLackingCoordinationException)
            {
                // don't log this Exception - the Client knows how to deal with it.
                throw;
            }
            catch (Exception Exp)
            {
                TLogging.Log("TServerLookups_PartnerInfo.PartnerLocationInternal exception: " + Exp.ToString(), TLoggingType.ToLogfile);
                TLogging.Log(Exp.StackTrace, TLoggingType.ToLogfile);
                throw;
            }
            finally
            {
                if (NewTransaction)
                {
                    DBAccess.GDBAccessObj.CommitTransaction();
                    TLogging.LogAtLevel(7, "TServerLookups_PartnerInfo.LocationPartnerLocationAndRestOnly: committed own transaction.");
                }
            }

            return ReturnValue;
        }
        /// <summary>
        /// todoComment
        /// </summary>
        /// <param name="APartnerLocationRow"></param>
        /// <param name="APartnerKey"></param>
        /// <param name="APartnerClass"></param>
        /// <param name="AAddressAddedOrChangedPromotionDT"></param>
        /// <param name="ALocationPK"></param>
        /// <param name="AReadTransaction"></param>
        /// <returns></returns>
        private static Boolean CheckFamilyMemberPropagation(PPartnerLocationRow APartnerLocationRow,
            Int64 APartnerKey,
            String APartnerClass,
            ref PartnerAddressAggregateTDSAddressAddedOrChangedPromotionTable AAddressAddedOrChangedPromotionDT,
            TLocationPK ALocationPK,
            TDBTransaction AReadTransaction)
        {
            Boolean ReturnValue;
            DataView AddressAddedOrChangedPromotionDV;
            PartnerAddressAggregateTDSAddressAddedOrChangedPromotionRow AddressAddedOrChangedRow;
            Boolean FoundFamilyMembers;

//              TLogging.LogAtLevel(9, "CheckFamilyMemberPropagation for Location " + APartnerLocationRow.LocationKey.ToString() +
//                    ": AAddressAddedOrChangedPromotionDT.Rows.Count: " + AAddressAddedOrChangedPromotionDT.Rows.Count.ToString());
//              TLogging.LogAtLevel(9, "CheckFamilyMemberPropagation: ALocationPK.LocationKey: " + ALocationPK.LocationKey.ToString());

            // Check if there is a Parameter Row for the LocationKey we are looking at
            AddressAddedOrChangedPromotionDV = new DataView(AAddressAddedOrChangedPromotionDT,
                PartnerAddressAggregateTDSAddressAddedOrChangedPromotionTable.GetSiteKeyDBName() + " = " + ALocationPK.SiteKey.ToString() + " AND " +
                PartnerAddressAggregateTDSAddressAddedOrChangedPromotionTable.GetLocationKeyDBName() + " = " + ALocationPK.LocationKey.ToString() +
                " AND " + PartnerAddressAggregateTDSAddressAddedOrChangedPromotionTable.GetLocationAddedDBName() + " = true AND " +
                PartnerAddressAggregateTDSAddressAddedOrChangedPromotionTable.GetUserAnswerDBName() + " <> ''''",
                "",
                DataViewRowState.CurrentRows);

            // No, there isn't one: perform DB check
            if (AddressAddedOrChangedPromotionDV.Count == 0)
            {
                if (PPersonAccess.CountViaPFamily(APartnerKey, AReadTransaction) > 0)
                {
                    FoundFamilyMembers = true;
                }
                else
                {
                    FoundFamilyMembers = false;
                }

                if (FoundFamilyMembers)
                {
                    // Create a Parameter Row
//                  TLogging.LogAtLevel(9, "CheckFamilyMemberPropagation: Location " + APartnerLocationRow.LocationKey.ToString() + ": Partner is Family and has Family Members!");
                    AAddressAddedOrChangedPromotionDT = new PartnerAddressAggregateTDSAddressAddedOrChangedPromotionTable(
                        MPartnerConstants.ADDRESSADDEDORCHANGEDPROMOTION_TABLENAME);
                    AddressAddedOrChangedRow = AAddressAddedOrChangedPromotionDT.NewRowTyped(false);
                    AddressAddedOrChangedRow.SiteKey = ALocationPK.SiteKey;
                    AddressAddedOrChangedRow.LocationKey = ALocationPK.LocationKey;
                    AddressAddedOrChangedRow.LocationAdded = true;
                    AddressAddedOrChangedRow.LocationChange = false;
                    AddressAddedOrChangedRow.AnswerProcessedClientSide = false;
                    AddressAddedOrChangedRow.AnswerProcessedServerSide = false;
                    AAddressAddedOrChangedPromotionDT.Rows.Add(AddressAddedOrChangedRow);
                    ReturnValue = true;
                }
                else
                {
//                  TLogging.LogAtLevel(9, "CheckFamilyMemberPropagation: Location " + APartnerLocationRow.LocationKey.ToString() + ": found no Family Members.");
                    ReturnValue = false;
                }
            }
            else
            {
                // AAddressAddedOrChangedPromotionDT was passed in, holding parameters for the LocationKey we are looking at
                AddressAddedOrChangedRow = (PartnerAddressAggregateTDSAddressAddedOrChangedPromotionRow)AddressAddedOrChangedPromotionDV[0].Row;

                if (AddressAddedOrChangedRow.UserAnswer == "YES")
                {
//                  TLogging.LogAtLevel(9, "CheckFamilyMemberPropagation: AAddressAddedOrChangedPromotionDT tells me to propagate the new Location to all Family Members.");
                    AddressAddedOrChangedRow.AnswerProcessedClientSide = true;
                    AddressAddedOrChangedRow.AcceptChanges();
                    ReturnValue = true;
                }
                else
                {
//                  TLogging.LogAtLevel(9, "CheckFamilyMemberPropagation: AAddressAddedOrChangedPromotionDT tells me NOT to propagate the new Location.");
                    AddressAddedOrChangedRow.AnswerProcessedClientSide = true;
                    AddressAddedOrChangedRow.AcceptChanges();
                    ReturnValue = false;
                }
            }

            return ReturnValue;
        }
        /// <summary>
        /// Retrieves PartnerLocation information and the rest of the PartnerInfo data, but not the
        /// 'Head' data.
        /// </summary>
        /// <param name="APartnerKey">PartnerKey of Partner to find the short name for</param>
        /// <param name="ALocationKey" >Location Key of the Location that the information should be
        /// retrieved for.</param>
        /// <param name="APartnerInfoDS">Typed DataSet that contains the requested data.</param>
        /// <param name="AIncludeRest">Include 'Rest' data as well</param>
        private static bool PartnerLocationInternal(Int64 APartnerKey, TLocationPK ALocationKey,
            ref PartnerInfoTDS APartnerInfoDS,
            bool AIncludeRest)
        {
            bool ReturnValue = false;
            TDBTransaction ReadTransaction;
            Boolean NewTransaction = false;
            PPartnerRow PartnerDR;

            ReadTransaction = DBAccess.GDBAccessObj.GetNewOrExistingTransaction(IsolationLevel.ReadCommitted,
                TEnforceIsolationLevel.eilMinimum,
                out NewTransaction);

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

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

                    /*
                     * Partner exists --> we can go ahead with data gathering
                     */
                    PartnerLocationInternal(APartnerKey, ALocationKey, ReadTransaction, ref APartnerInfoDS);

                    if (AIncludeRest)
                    {
                        RestInternal(PartnerDR, ReadTransaction, ref APartnerInfoDS);
                    }

                    ReturnValue = true;
                }
            }
            catch (ESecurityPartnerAccessDeniedException)
            {
                // don't log this exception - this is thrown on purpose here and the Client knows how to deal with it.
                throw;
            }
            catch (EDBAccessLackingCoordinationException)
            {
                // don't log this Exception - the Client knows how to deal with it.
                throw;
            }
            catch (Exception Exp)
            {
                TLogging.Log("TServerLookups_PartnerInfo.PartnerLocationInternal exception: " + Exp.ToString(), TLoggingType.ToLogfile);
                TLogging.Log(Exp.StackTrace, TLoggingType.ToLogfile);
                throw;
            }
            finally
            {
                if (NewTransaction)
                {
                    DBAccess.GDBAccessObj.CommitTransaction();
                    TLogging.LogAtLevel(7, "TServerLookups_PartnerInfo.PartnerLocationInternal: committed own transaction.");
                }
            }

            return ReturnValue;
        }
예제 #32
0
        /// <summary>
        /// Adds a Partner to an Extract, if they are not already present
        /// </summary>
        /// <param name="APartnerKey">PartnerKey of Partner</param>
        /// <param name="ALocationPK">Location PK of a Partner's PartnerLocation
        /// (usually the LocationPK of the 'Best Address' of the Partner).</param>
        /// <param name="AExtractId">ExtractId of the Extract that the Partner should
        /// get added to.</param>
        /// <returns>True if the Partner was added to the Extract, otherwise false.</returns>
        public static bool AddPartnerToExtract(Int64 APartnerKey,
            TLocationPK ALocationPK, int AExtractId)
        {
            TDBTransaction Transaction = null;
            bool SubmissionOK = false;
            MExtractTable TemplateTable;
            MExtractRow TemplateRow;
            MExtractRow NewRow;

            if (APartnerKey > 0)
            {
                DBAccess.GDBAccessObj.GetNewOrExistingAutoTransaction(IsolationLevel.Serializable, ref Transaction, ref SubmissionOK,
                    delegate
                    {
                        /*
                         * First check whether the Partner isn't already in that Extract
                         */
                        TemplateTable = new MExtractTable();
                        TemplateRow = TemplateTable.NewRowTyped(false);
                        TemplateRow.ExtractId = AExtractId;
                        TemplateRow.PartnerKey = APartnerKey;

                        if (MExtractAccess.CountUsingTemplate(TemplateRow, null, Transaction) == 0)
                        {
                            /*
                             * Add Partner to Extract.
                             */
                            NewRow = TemplateTable.NewRowTyped(false);
                            NewRow.ExtractId = AExtractId;
                            NewRow.PartnerKey = APartnerKey;
                            NewRow.SiteKey = ALocationPK.SiteKey;
                            NewRow.LocationKey = ALocationPK.LocationKey;
                            TemplateTable.Rows.Add(NewRow);

                            MExtractAccess.SubmitChanges(TemplateTable, Transaction);

                            SubmissionOK = true;
                        }
                        else
                        {
                            // Partner is already in that Extract -> Partner does not get added.
                            SubmissionOK = false;
                        }
                    });
            }
            else
            {
                // Invalid PartnerKey -> return false;
                SubmissionOK = false;
            }

            return SubmissionOK;
        }
 /// <summary>
 /// Retrieves PartnerLocation information.
 /// </summary>
 /// <param name="APartnerKey">PartnerKey of Partner to find the short name for</param>
 /// <param name="ALocationKey" >Location Key of the Location that the information should be
 /// retrieved for.</param>
 /// <param name="AReadTransaction">Open Database Transaction.</param>
 /// <param name="APartnerInfoDS">Typed DataSet that contains the requested data.</param>
 private static void PartnerLocationInternal(Int64 APartnerKey, TLocationPK ALocationKey,
     TDBTransaction AReadTransaction,
     ref PartnerInfoTDS APartnerInfoDS)
 {
     /*
      * Load PartnerLocation Information; this gets merged into the already retrieved
      * information in APartnerInfoDS (eg. 'Head' data)
      */
     APartnerInfoDS.Merge(TPPartnerAddressAggregate.LoadByPrimaryKey(
             APartnerKey, ALocationKey.SiteKey, ALocationKey.LocationKey, AReadTransaction));
 }
        /// <summary>
        /// Iterates through all PPartnerLocation DataRows and checks whether any has a
        /// SiteKey and LocationKey with the Original values that we are looking for to
        /// be able to return the corresponding PLocation DataRow.
        ///
        /// </summary>
        /// <param name="ALocationPK">Primary Key that the searched for PLocation DataRow should
        /// have had orignally</param>
        /// <returns>PLocation DataRow if found, otherwise nil
        /// </returns>
        private PLocationRow FindLocationRowWithOriginalKey(TLocationPK ALocationPK)
        {
            PLocationRow ReturnValue;

            ReturnValue = null;

            /*
             * Iterate through all PPartnerLocation DataRows and check whether any has a PK with
             * the Original values that we are looking for.
             */
            foreach (PPartnerLocationRow PartnerLocationRow in FMainDS.PPartnerLocation.Rows)
            {
                // MessageBox.Show('FindLocationRowWithOriginalKey: SiteKey: ' + Convert.ToInt64(PartnerLocationRow[PPartnerLocationTable.GetSiteKeyDBName(),
                // DataRowVersion.Original]).ToString + '; LocationKey: ' +
                // Convert.ToInt32(PartnerLocationRow[PPartnerLocationTable.GetLocationKeyDBName(),
                // DataRowVersion.Original]).ToString);
                if ((Convert.ToInt64(PartnerLocationRow[PLocationTable.GetSiteKeyDBName(),
                                                        DataRowVersion.Original]) == ALocationPK.SiteKey)
                    && (Convert.ToInt32(PartnerLocationRow[PLocationTable.GetLocationKeyDBName(),
                                                           DataRowVersion.Original]) == ALocationPK.LocationKey))
                {
                    // Find the PLocationRow that has the same SiteKey and LocationKey than the
                    // found PPartnerLocationRow and return it!
                    ReturnValue = (PLocationRow)FMainDS.PLocation.Rows.Find(new Object[] { PartnerLocationRow.SiteKey, PartnerLocationRow.LocationKey });
                }
            }

            return ReturnValue;
        }
 /// <summary>
 /// Retrieves Location and PartnerLocation information and the rest of the PartnerInfo data,
 /// but not the 'Head' data.
 /// </summary>
 /// <param name="APartnerKey">PartnerKey of Partner to find the PartnerInfo data for</param>
 /// <param name="ALocationKey" >Location Key of the Location that the information should be
 /// retrieved for.</param>
 /// <param name="APartnerInfoDS">Typed DataSet that contains the requested data.</param>
 /// <returns>True if Partner exists, otherwise false.</returns>
 public static bool LocationPartnerLocationOnly(Int64 APartnerKey, TLocationPK ALocationKey,
     ref PartnerInfoTDS APartnerInfoDS)
 {
     return LocationPartnerLocationInternal(APartnerKey, ALocationKey, ref APartnerInfoDS, false);
 }