Example #1
0
        /// <summary>
        /// Copies over all columns of a Location Row, except the Primary Key columns
        /// and the last four columns (containing creation and change information).
        ///
        /// </summary>
        /// <param name="ACopyLocationsRow">Row to copy data from</param>
        /// <param name="ADestinationLocationsRow">Row to copy data to
        /// </param>
        /// <returns>void</returns>
        public static void CopyLocationData(PLocationRow ACopyLocationsRow, PLocationRow ADestinationLocationsRow)
        {
            ADestinationLocationsRow.Locality    = ACopyLocationsRow.Locality;
            ADestinationLocationsRow.StreetName  = ACopyLocationsRow.StreetName;
            ADestinationLocationsRow.Address3    = ACopyLocationsRow.Address3;
            ADestinationLocationsRow.City        = ACopyLocationsRow.City;
            ADestinationLocationsRow.PostalCode  = ACopyLocationsRow.PostalCode;
            ADestinationLocationsRow.County      = ACopyLocationsRow.County;
            ADestinationLocationsRow.CountryCode = ACopyLocationsRow.CountryCode;

            // Created/Modified info
            if (!ACopyLocationsRow.IsDateCreatedNull())
            {
                ADestinationLocationsRow.DateCreated = ACopyLocationsRow.DateCreated;
            }

            if (!ACopyLocationsRow.IsDateModifiedNull())
            {
                ADestinationLocationsRow.DateModified = ACopyLocationsRow.DateModified;
            }

            ADestinationLocationsRow.CreatedBy = TSaveConvert.StringColumnToString(((PLocationTable)ACopyLocationsRow.Table).ColumnCreatedBy,
                                                                                   ACopyLocationsRow);
            ADestinationLocationsRow.ModifiedBy = TSaveConvert.StringColumnToString(((PLocationTable)ACopyLocationsRow.Table).ColumnModifiedBy,
                                                                                    ACopyLocationsRow);
            ADestinationLocationsRow.ModificationId = ACopyLocationsRow.ModificationId;
        }
Example #2
0
        public static PartnerEditTDS CreateNewPartner(
            string APartnerClass,
            out List <string> ASubscriptions,
            out List <string> APartnerTypes,
            out string ADefaultEmailAddress,
            out string ADefaultPhoneMobile,
            out string ADefaultPhoneLandline)
        {
            TPartnerEditUIConnector partneredit = new TPartnerEditUIConnector();
            string TmpSiteCountryCode;
            Int64  SiteKey = DomainManager.GSiteKey;

            PartnerEditTDS MainDS = partneredit.GetDataNewPartner(
                SiteKey,
                NewPartnerKey(),
                SharedTypes.PartnerClassStringToEnum(APartnerClass),
                String.Empty,
                String.Empty,
                false,
                -1,
                -1,
                -1,
                out TmpSiteCountryCode);

            MainDS.PPartner[0].ReceiptLetterFrequency = "Annual";

            PLocationRow location = MainDS.PLocation.NewRowTyped();

            location.SiteKey = SiteKey;
            // TODO: read country code from SystemDefaults table
            location.CountryCode = "DE";
            location.LocationKey = -1;
            MainDS.PLocation.Rows.Add(location);

            TDBTransaction Transaction = new TDBTransaction();

            DBAccess.ReadTransaction(ref Transaction,
                                     delegate
            {
                PCountryAccess.LoadAll(MainDS, Transaction);
                PPublicationAccess.LoadAll(MainDS, Transaction);
                PPartnerStatusAccess.LoadAll(MainDS, Transaction);

                PTypeRow templateRow   = MainDS.PType.NewRowTyped();
                templateRow.SystemType = false;
                templateRow.SetTypeDeletableNull();
                templateRow.SetDateCreatedNull();
                PTypeAccess.LoadUsingTemplate(MainDS, templateRow, Transaction);
            });

            APartnerTypes         = new List <string>();
            ASubscriptions        = new List <string>();
            ADefaultEmailAddress  = String.Empty;
            ADefaultPhoneMobile   = String.Empty;
            ADefaultPhoneLandline = String.Empty;

            return(MainDS);
        }
 /// <summary>
 /// Allows copying of an Address that the user has found (using Menu 'Edit'->'Find
 /// New Address...') into the currently edited Address.
 /// </summary>
 /// <param name="AFoundAddressLocationRow">DataRow containing the Location information
 /// for the found Address.
 /// </param>
 public void CopyFoundAddressData(PLocationRow AFoundAddressLocationRow)
 {
     if (FCurrentModuleTabGroup == TPartnerEditScreenLogic.TModuleTabGroupEnum.mtgPartner)
     {
         ucoPartnerTabSet.CopyFoundAddressData(AFoundAddressLocationRow);
     }
     else
     {
         throw new EOPAppException("This Menu item must only be used when the Partner Data Tab Group is shown");
     }
 }
Example #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();
        }
Example #5
0
        private static void CreateAddress(ref PartnerEditTDS AMainDS, TApplicationFormData APartnerData, Int64 ANewPartnerKey)
        {
            // the webform prevents adding empty addresses

            // for children and staff, we do not require to enter an address
            if (APartnerData.street == null)
            {
                PPartnerLocationRow emptyPartnerLocation = AMainDS.PPartnerLocation.NewRowTyped(true);
                emptyPartnerLocation.SiteKey       = 0;
                emptyPartnerLocation.LocationKey   = 0;
                emptyPartnerLocation.PartnerKey    = ANewPartnerKey;
                emptyPartnerLocation.SendMail      = false;
                emptyPartnerLocation.DateEffective = DateTime.Now;
                emptyPartnerLocation.LocationType  = "HOME";
                emptyPartnerLocation.EmailAddress  = APartnerData.email;
                AMainDS.PPartnerLocation.Rows.Add(emptyPartnerLocation);
                return;
            }

            // TODO: avoid duplicate addresses, reuse existing locations
            PLocationRow location = AMainDS.PLocation.NewRowTyped(true);

            location.LocationKey = (AMainDS.PLocation.Rows.Count + 1) * -1;
            location.SiteKey     = 0;

            location.CountryCode = APartnerData.country;
            location.County      = APartnerData.county;
            location.StreetName  = APartnerData.street;
            location.City        = APartnerData.city;
            location.PostalCode  = APartnerData.postcode;
            AMainDS.PLocation.Rows.Add(location);

            PPartnerLocationRow partnerlocation = AMainDS.PPartnerLocation.NewRowTyped(true);

            partnerlocation.SiteKey         = 0;
            partnerlocation.LocationKey     = location.LocationKey;
            partnerlocation.PartnerKey      = ANewPartnerKey;
            partnerlocation.SendMail        = true;
            partnerlocation.DateEffective   = DateTime.Now;
            partnerlocation.LocationType    = "HOME";
            partnerlocation.EmailAddress    = APartnerData.email;
            partnerlocation.TelephoneNumber = APartnerData.phone;
            partnerlocation.MobileNumber    = APartnerData.mobilephone;
            AMainDS.PPartnerLocation.Rows.Add(partnerlocation);
        }
Example #6
0
        /// <summary>
        /// Private method used by ExportPartners().
        /// For the given partnerKey, updates given references countryCode and siteKey.
        /// If there is no location for the given partnerKey, leaves them as they are.
        /// </summary>
        /// <param name="MainDS">Reference to the already filled Datastructure</param>
        /// <param name="partnerKey"></param>
        /// <param name="countryCode"></param>
        /// <param name="siteKey"></param>
        /// <returns>
        /// True: if a location was found for given key and the countryCode
        /// and siteKey were updated. False otherwise.
        /// </returns>
        private static bool UpdateCountryAndSiteForGivenPK(
            PartnerEditTDS MainDS,
            long partnerKey,
            ref string countryCode /* default could be "" */,
            ref Int64 siteKey /* default could be -1 */
            )
        {
            bool retval = false;
            // Find partnerLocation for given partner_key
            DataView partnerLocationView = MainDS.PPartnerLocation.DefaultView;

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

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

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

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

            return(retval);
        }
        /// create a new location
        public static void CreateNewLocation(Int64 APartnerKey, PartnerEditTDS AMainDS)
        {
            // avoid duplicate addresses: StreetName contains the partner key
            PLocationRow LocationRow = AMainDS.PLocation.NewRowTyped();

            LocationRow.SiteKey     = DomainManager.GSiteKey;
            LocationRow.LocationKey = -1;
            LocationRow.StreetName  = APartnerKey.ToString() + " Nowhere Lane";
            LocationRow.PostalCode  = "LO2 2CX";
            LocationRow.City        = "London";
            LocationRow.CountryCode = "99";
            AMainDS.PLocation.Rows.Add(LocationRow);

            PPartnerLocationRow PartnerLocationRow = AMainDS.PPartnerLocation.NewRowTyped();

            PartnerLocationRow.SiteKey     = LocationRow.SiteKey;
            PartnerLocationRow.PartnerKey  = APartnerKey;
            PartnerLocationRow.LocationKey = LocationRow.LocationKey;
            AMainDS.PPartnerLocation.Rows.Add(PartnerLocationRow);
        }
Example #8
0
        private void WriteLocation(PLocationRow ALocationRow, PPartnerLocationRow APartnerLocationRow)
        {
            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);
            Write(APartnerLocationRow.IsEmailAddressNull() ? "" : APartnerLocationRow.EmailAddress);
            Write(APartnerLocationRow.IsTelephoneNumberNull() ? "" : APartnerLocationRow.TelephoneNumber);
            Write(APartnerLocationRow.IsExtensionNull() ? 0 : APartnerLocationRow.Extension);
            Write(APartnerLocationRow.IsFaxNumberNull() ? "" : APartnerLocationRow.FaxNumber);
            Write(APartnerLocationRow.IsFaxExtensionNull() ? 0 : APartnerLocationRow.FaxExtension);
            WriteLine();
        }
        /// <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>
        /// todoComment
        /// </summary>
        /// <param name="ALocationRow"></param>
        /// <param name="APartnerKey"></param>
        /// <param name="AExistingLocationParametersDT"></param>
        /// <param name="AReadTransaction"></param>
        /// <param name="AExistingSiteKey"></param>
        /// <param name="AExistingLocationKey"></param>
        /// <returns></returns>
        private static Boolean CheckReUseExistingLocation(PLocationRow ALocationRow,
            Int64 APartnerKey,
            ref PartnerAddressAggregateTDSSimilarLocationParametersTable AExistingLocationParametersDT,
            TDBTransaction AReadTransaction,
            out Int64 AExistingSiteKey,
            out Int32 AExistingLocationKey)
        {
            Boolean ReturnValue;
            PLocationTable MatchingLocationsDT;
            Boolean FoundSimilarLocation;
            PartnerAddressAggregateTDSSimilarLocationParametersRow SimilarLocationRow;
            PartnerAddressAggregateTDSSimilarLocationParametersRow SimilarLocationParameterRow;
            DataView ExistingLocationParametersDV;
            int LocationUsedByNPartners;
            int Counter;
            PLocationRow MatchingLocationRow;

            AExistingSiteKey = 0;
            AExistingLocationKey = 0;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                MatchingLocationsDT = new PLocationTable();

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

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

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

                #endregion

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

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

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

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

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

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

            return ReturnValue;
        }
        /// <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;
        }
Example #12
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;
            }
        }
Example #13
0
        public static DataConsentTDS LastKnownEntry(
            Int64 APartnerKey,
            string ADataType
            )
        {
            TDBTransaction       T            = new TDBTransaction();
            TDataBase            DB           = DBAccess.Connect("Get Last known entry");
            DataConsentTDS       Set          = new DataConsentTDS();
            List <OdbcParameter> SQLParameter = new List <OdbcParameter>();

            DB.ReadTransaction(ref T, delegate {
                string sql = "SELECT " +
                             "`p_consent_history`.*, " +
                             "GROUP_CONCAT(`p_consent_history_permission`.`p_purpose_code_c` SEPARATOR ',') AS `AllowedPurposes` " +
                             "FROM `p_consent_history` " +
                             "LEFT JOIN `p_consent_history_permission` " +
                             "ON `p_consent_history`.`p_entry_id_i` = `p_consent_history_permission`.`p_consent_history_entry_i` " +
                             "WHERE `p_consent_history`.`p_partner_key_n` = ? " +
                             "AND `p_consent_history`.`p_type_c` = ? " +
                             "GROUP BY `p_consent_history`.`p_entry_id_i` " +
                             "ORDER BY `p_consent_history`.`p_entry_id_i` DESC " +
                             "LIMIT 1";

                SQLParameter.Add(new OdbcParameter("PartnerKey", OdbcType.BigInt)
                {
                    Value = APartnerKey
                });
                SQLParameter.Add(new OdbcParameter("DataType", OdbcType.VarChar)
                {
                    Value = ADataType
                });

                DB.SelectDT(Set.PConsentHistory, sql, T, SQLParameter.ToArray());

                if (Set.PConsentHistory.Count == 0)
                {
                    // there is no consent yet
                    // do we have a value at all?
                    List <string> Subscriptions;
                    List <string> PartnerTypes;
                    string DefaultEmailAddress;
                    string DefaultPhoneMobile;
                    string DefaultPhoneLandline;
                    PartnerEditTDS PartnerDS = TSimplePartnerEditWebConnector.GetPartnerDetails(APartnerKey,
                                                                                                out Subscriptions,
                                                                                                out PartnerTypes,
                                                                                                out DefaultEmailAddress,
                                                                                                out DefaultPhoneMobile,
                                                                                                out DefaultPhoneLandline);

                    if (ADataType == MPartnerConstants.CONSENT_TYPE_ADDRESS)
                    {
                        // what about new contact?
                        PLocationRow locationRow = null;

                        if (PartnerDS.PLocation.Rows.Count > 0)
                        {
                            locationRow = PartnerDS.PLocation[0];
                        }
                        else
                        {
                            locationRow = PartnerDS.PLocation.NewRowTyped();
                        }

                        PConsentHistoryRow row = Set.PConsentHistory.NewRowTyped();
                        row.EntryId            = -1;
                        row.PartnerKey         = APartnerKey;
                        row.Type        = ADataType;
                        row.Value       = locationRow.StreetName + ", " + locationRow.PostalCode + " " + locationRow.City + ", " + locationRow.CountryCode;
                        row.ConsentDate = DateTime.Today;
                        Set.PConsentHistory.Rows.Add(row);
                    }

                    if (ADataType == MPartnerConstants.CONSENT_TYPE_EMAIL)
                    {
                        PConsentHistoryRow row = Set.PConsentHistory.NewRowTyped();
                        row.EntryId            = -1;
                        row.PartnerKey         = APartnerKey;
                        row.Type        = ADataType;
                        row.Value       = DefaultEmailAddress;
                        row.ConsentDate = DateTime.Today;
                        Set.PConsentHistory.Rows.Add(row);
                    }

                    if (ADataType == MPartnerConstants.CONSENT_TYPE_LANDLINE)
                    {
                        PConsentHistoryRow row = Set.PConsentHistory.NewRowTyped();
                        row.EntryId            = -1;
                        row.PartnerKey         = APartnerKey;
                        row.Type        = ADataType;
                        row.Value       = DefaultPhoneLandline;
                        row.ConsentDate = DateTime.Today;
                        Set.PConsentHistory.Rows.Add(row);
                    }

                    if (ADataType == MPartnerConstants.CONSENT_TYPE_MOBILE)
                    {
                        PConsentHistoryRow row = Set.PConsentHistory.NewRowTyped();
                        row.EntryId            = -1;
                        row.PartnerKey         = APartnerKey;
                        row.Type        = ADataType;
                        row.Value       = DefaultPhoneMobile;
                        row.ConsentDate = DateTime.Today;
                        Set.PConsentHistory.Rows.Add(row);
                    }
                }

                PConsentChannelAccess.LoadAll(Set, T);
                PConsentPurposeAccess.LoadAll(Set, T);
            });

            return(Set);
        }
        /// <summary>
        /// set parameters before screen is opened
        /// </summary>
        /// <param name="AAddressAddedOrChangedPromotionDR"></param>
        /// <param name="APartnerSharingLocationDV"></param>
        /// <param name="ALocationRow">Location Row that has been modified</param>
        /// <param name="AOtherFormTitle">Fill this if form should not use standard title</param>
        /// <param name="AOtherExplanation">Fill this if explanation should not be standard one</param>
        /// <returns></returns>
        public void SetParameters(PartnerAddressAggregateTDSAddressAddedOrChangedPromotionRow AAddressAddedOrChangedPromotionDR,
            DataView APartnerSharingLocationDV,
            PLocationRow ALocationRow,
            String AOtherFormTitle,
            String AOtherExplanation)
        {
            //TODOWB FAddressAddedOrChangedPromotionDR = AAddressAddedOrChangedPromotionDR;
            FPartnerSharingLocationDV = APartnerSharingLocationDV;

            /* MessageBox.Show('FPartnerSharingLocationDV.Count: ' + FPartnerSharingLocationDV.Count.ToString); */
            //TODOWB FLocationRow = ALocationRow;
            ApplyText(AOtherFormTitle, AOtherExplanation, ALocationRow);
        }
        /// <summary>
        /// todoComment
        /// </summary>
        /// <param name="ALocationRow"></param>
        /// <param name="APartnerKey"></param>
        /// <param name="AAddressAddedOrChangedPromotionDT"></param>
        /// <param name="AReadTransaction"></param>
        /// <param name="AUpdateLocation"></param>
        /// <param name="ACreateLocation"></param>
        /// <param name="ACreateLocationOtherPartnerKeys"></param>
        /// <param name="AChangePromotionParametersDT"></param>
        /// <returns></returns>
        private static Boolean CheckLocationChange(PLocationRow ALocationRow,
            Int64 APartnerKey,
            ref PartnerAddressAggregateTDSAddressAddedOrChangedPromotionTable AAddressAddedOrChangedPromotionDT,
            TDBTransaction AReadTransaction,
            out Boolean AUpdateLocation,
            out Boolean ACreateLocation,
            out Int64[] ACreateLocationOtherPartnerKeys,
            out PartnerAddressAggregateTDSChangePromotionParametersTable AChangePromotionParametersDT)
        {
            Boolean ReturnValue;

            PartnerAddressAggregateTDSChangePromotionParametersRow AddressAddedPromotionRow;

            ACreateLocation = false;
            AUpdateLocation = false;

            ACreateLocationOtherPartnerKeys = null;
            AChangePromotionParametersDT = null;

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

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

            // No, there isn't one  therefore create one
            if (AddressAddedOrChangedPromotionDV.Count == 0)
            {
//              TLogging.LogAtLevel(9, "CheckLocationChange: Location " + ALocationRow.LocationKey.ToString() +
//                  ": Location has been changed and is referenced by other Partners!");
                AAddressAddedOrChangedPromotionDT = new PartnerAddressAggregateTDSAddressAddedOrChangedPromotionTable(
                    MPartnerConstants.ADDRESSADDEDORCHANGEDPROMOTION_TABLENAME);
                PartnerAddressAggregateTDSAddressAddedOrChangedPromotionRow AddressAddedOrChangedRow =
                    AAddressAddedOrChangedPromotionDT.NewRowTyped(false);
                AddressAddedOrChangedRow.SiteKey = ALocationRow.SiteKey;
                AddressAddedOrChangedRow.LocationKey = ALocationRow.LocationKey;
                AddressAddedOrChangedRow.PartnerKey = APartnerKey;
                AddressAddedOrChangedRow.LocationChange = true;
                AddressAddedOrChangedRow.LocationAdded = false;
                AddressAddedOrChangedRow.AnswerProcessedClientSide = false;
                AddressAddedOrChangedRow.AnswerProcessedServerSide = false;
                AAddressAddedOrChangedPromotionDT.Rows.Add(AddressAddedOrChangedRow);
                #region Build ChangePromotionParameters DataTable
                AChangePromotionParametersDT = new PartnerAddressAggregateTDSChangePromotionParametersTable(
                    MPartnerConstants.ADDRESSCHANGEPROMOTIONPARAMETERS_TABLENAME);

                // Load data for all other Partners that reference the PartnerLocation
                OdbcParameter[] ParametersArray = new OdbcParameter[3];
                ParametersArray[0] = new OdbcParameter("", OdbcType.Decimal, 10);
                ParametersArray[0].Value = (System.Object)(APartnerKey);
                ParametersArray[1] = new OdbcParameter("", OdbcType.Decimal, 10);
                ParametersArray[1].Value = (System.Object)(ALocationRow.SiteKey);
                ParametersArray[2] = new OdbcParameter("", OdbcType.Int);
                ParametersArray[2].Value = (System.Object)(ALocationRow.LocationKey);
                DataTable OtherPartnerLocationReferencesDT = DBAccess.GDBAccessObj.SelectDT(
                    "SELECT PUB_" + PPartnerLocationTable.GetTableDBName() + '.' + PPartnerLocationTable.GetPartnerKeyDBName() + ", " +
                    PPartnerTable.GetPartnerShortNameDBName() + ", " +
                    PPartnerTable.GetPartnerClassDBName() + ", " + PPartnerLocationTable.GetTelephoneNumberDBName() + ", " +
                    PPartnerLocationTable.GetLocationTypeDBName() + ' ' + "FROM PUB_" + PPartnerTable.GetTableDBName() + " INNER JOIN PUB_" +
                    PPartnerLocationTable.GetTableDBName() + " ON PUB_" + PPartnerTable.GetTableDBName() + '.' +
                    PPartnerTable.GetPartnerKeyDBName() +
                    " = PUB_" + PPartnerLocationTable.GetTableDBName() + '.' + PPartnerLocationTable.GetPartnerKeyDBName() + ' ' + "WHERE    PUB_" +
                    PPartnerLocationTable.GetTableDBName() + '.' + PPartnerLocationTable.GetPartnerKeyDBName() + " <> ? " + "AND    " +
                    PPartnerLocationTable.GetSiteKeyDBName() + " = ? " + "AND    " + PPartnerLocationTable.GetLocationKeyDBName() + " = ?",
                    "OtherPartnerLocationReferencesDT", AReadTransaction, ParametersArray);

                // Don't need these columns for the moment, but it would be nice to have them later on
                // PPartnerLocationTable.GetSendMailDBName + ', ' +
                // PPartnerLocationTable.GetDateEffectiveDBName + ', ' +
                // PPartnerLocationTable.GetDateGoodUntilDBName + ', ' +
                // Insert data into the ChangePromotionParameters DataTable
                for (int Counter = 0; Counter <= OtherPartnerLocationReferencesDT.Rows.Count - 1; Counter += 1)
                {
                    DataRow OtherPartnerLocationReferenceRow = OtherPartnerLocationReferencesDT.Rows[Counter];
                    AddressAddedPromotionRow = AChangePromotionParametersDT.NewRowTyped(false);
                    AddressAddedPromotionRow.SiteKey = ALocationRow.SiteKey;
                    AddressAddedPromotionRow.LocationKey = (Int32)ALocationRow.LocationKey;
                    AddressAddedPromotionRow.PartnerKey = Convert.ToInt64(
                        OtherPartnerLocationReferenceRow[PPartnerLocationTable.GetPartnerKeyDBName()]);
                    AddressAddedPromotionRow.PartnerShortName = OtherPartnerLocationReferenceRow[PPartnerTable.GetPartnerShortNameDBName()].ToString();
                    AddressAddedPromotionRow.PartnerClass = OtherPartnerLocationReferenceRow[PPartnerTable.GetPartnerClassDBName()].ToString();
                    // AddressAddedPromotionRow.SendMail :=
                    // Convert.ToBoolean(OtherPartnerLocationReferenceRow[PPartnerLocationTable.GetSendMailDBName]);
                    // if not OtherPartnerLocationReferenceRow.IsNull(
                    // PPartnerLocationTable.GetDateEffectiveDBName) then
                    // begin
                    // AddressAddedPromotionRow.DateEffective :=
                    // Convert.ToDateTime(OtherPartnerLocationReferenceRow[PPartnerLocationTable.GetDateEffectiveDBName]);
                    // end;
                    // if not OtherPartnerLocationReferenceRow.IsNull(
                    // PPartnerLocationTable.GetDateGoodUntilDBName) then
                    // begin
                    // AddressAddedPromotionRow.DateGoodUntil :=
                    // Convert.ToDateTime(OtherPartnerLocationReferenceRow[PPartnerLocationTable.GetDateGoodUntilDBName]);
                    // end;
                    AddressAddedPromotionRow.LocationType = OtherPartnerLocationReferenceRow[PPartnerLocationTable.GetLocationTypeDBName()].ToString();
                    AChangePromotionParametersDT.Rows.Add(AddressAddedPromotionRow);
                }

//             TLogging.LogAtLevel(9, "CheckLocationChange: Location " + ALocationRow.LocationKey.ToString() + ": inserted PartnerLocation data of " +
//                  AChangePromotionParametersDT.Rows.Count.ToString() + " other Partners that reference this Location into AChangePromotionParametersDT!");
                #endregion
                ReturnValue = true;
            }
            else
            {
                // AAddressAddedOrChangedPromotionDT was passed in, holding parameters for the LocationKey we are looking at
                PartnerAddressAggregateTDSAddressAddedOrChangedPromotionRow AddressAddedOrChangedRow =
                    (PartnerAddressAggregateTDSAddressAddedOrChangedPromotionRow)AddressAddedOrChangedPromotionDV[0].Row;

                if (AddressAddedOrChangedRow.UserAnswer == "CHANGE-NONE")
                {
//                  TLogging.LogAtLevel(9, "CheckLocationChange: AAddressAddedOrChangedPromotionDT tells me to CREATE the Location.");
                    ACreateLocation = true;

                    // Signal to calling procedure that the created location should not be
                    // assigned to any Partner other than the one we are currently processing.
                    ACreateLocationOtherPartnerKeys = new Int64[0];
                    AddressAddedOrChangedRow.AnswerProcessedClientSide = true;
                    AddressAddedOrChangedRow.AcceptChanges();
                    ReturnValue = true;
                }
                else if (AddressAddedOrChangedRow.UserAnswer.StartsWith("CHANGE-SOME"))
                {
//                  TLogging.LogAtLevel(9, "CheckLocationChange: AAddressAddedOrChangedPromotionDT tells me to CREATE the Location and assign it to selected partners.");
                    ACreateLocation = true;

                    // Parse the UserAnswer. It's format is 'CHANGESOME:PartnerKey1;PartnerKey2;PartnerKeyN'
                    string[] ChangeSomeArray = AddressAddedOrChangedRow.UserAnswer.Split(":,".ToCharArray());

                    // Build the ACreateLocationOtherPartnerKeys array from it to
                    // signal to calling procedure that the created location should be
                    // assigned to all the Partners contained in the Array.
                    ACreateLocationOtherPartnerKeys = new Int64[ChangeSomeArray.Length - 1];

                    for (int Counter = 1; Counter <= ChangeSomeArray.Length - 1; Counter += 1)
                    {
                        ACreateLocationOtherPartnerKeys[Counter - 1] = Convert.ToInt64(ChangeSomeArray[Counter]);
                    }

                    AddressAddedOrChangedRow.AnswerProcessedClientSide = true;
                    AddressAddedOrChangedRow.AcceptChanges();
                    ReturnValue = true;
                }
                else if (AddressAddedOrChangedRow.UserAnswer == "CHANGE-ALL")
                {
//                  TLogging.LogAtLevel(9, "CheckLocationChange: AAddressAddedOrChangedPromotionDT tells me to UPDATE the Location.");
                    AUpdateLocation = true;
                    AddressAddedOrChangedRow.AnswerProcessedClientSide = true;
                    AddressAddedOrChangedRow.AcceptChanges();
                    ReturnValue = true;
                }
                else
                {
//                  TLogging.LogAtLevel(9, "CheckLocationChange: AAddressAddedOrChangedPromotionDT tells me to CANCEL the changing of the Location.");
                    AddressAddedOrChangedRow.AnswerProcessedClientSide = true;
                    AddressAddedOrChangedRow.AcceptChanges();
                    ReturnValue = false;
                }
            }

            return ReturnValue;
        }
Example #16
0
 /// <summary>
 /// </summary>
 /// <param name="AFoundAddressLocationRow"></param>
 /// <param name="ADestinationLocationRow"></param>
 public static void CopyFoundAddressLocationData(PLocationRow AFoundAddressLocationRow, PLocationRow ADestinationLocationRow)
 {
     CopyLocationData(AFoundAddressLocationRow, ADestinationLocationRow);
 }
Example #17
0
        /// <summary>
        /// return an XmlDocument with all partner info;
        /// the partners are grouped by class, country, status, and sitekey
        /// </summary>
        /// <returns></returns>
        public static string ExportPartners()
        {
            PartnerEditTDS MainDS = new PartnerEditTDS();

            LoadDataFromDB(ref MainDS);

            // Group partners into categories.
            //
            // A partner's category is defined by his: class, country, status, and sitekey
            // It is stored as a string e.g. "FAMILY,DE,ACTIVE,0".
            //
            SortedList <string, List <long> > PartnerCategories = GroupPartnersIntoCategories(MainDS);

            // create XML structure for each category
            XmlDocument PartnerData = TYml2Xml.CreateXmlDocument();
            XmlNode     rootNode    = PartnerData.FirstChild.NextSibling;

            Int32 groupCounter = 0;

            foreach (string category in PartnerCategories.Keys)
            {
                // get category data
                groupCounter++;
                XmlElement groupNode = PartnerData.CreateElement("PartnerGroup" + groupCounter.ToString());
                rootNode.AppendChild(groupNode);

                Int32    partnerCounter  = 0;
                string[] categoryDetails = category.Split(new char[] { ',' });
                // may want to skip the categories with sitekey = -1
                // right now, we still export them and ignore the partners 0 and 1000000 later

                groupNode.SetAttribute("class", categoryDetails[0]);
                groupNode.SetAttribute("Country", categoryDetails[1]);
                groupNode.SetAttribute("status", categoryDetails[2]);
                groupNode.SetAttribute("SiteKey", categoryDetails[3]);

                List <long> partnerKeys = PartnerCategories[category];

                foreach (long partnerKey in partnerKeys)
                {
                    if ((partnerKey != 0) && (partnerKey != 1000000)) // skip organization root and the 0 when exporting
                    {
                        MainDS.PPartner.DefaultView.RowFilter = PPartnerTable.GetPartnerKeyDBName() + "=" + partnerKey.ToString();
                        PPartnerRow partnerRow = (PPartnerRow)MainDS.PPartner.DefaultView[0].Row;

                        PFamilyRow familyRow = null;

                        if (partnerRow.PartnerClass == MPartnerConstants.PARTNERCLASS_FAMILY)
                        {
                            MainDS.PFamily.DefaultView.RowFilter = PFamilyTable.GetPartnerKeyDBName() + "=" + partnerKey.ToString();
                            familyRow = (PFamilyRow)MainDS.PFamily.DefaultView[0].Row;
                        }

                        PPersonRow personRow = null;

                        if (partnerRow.PartnerClass == MPartnerConstants.PARTNERCLASS_PERSON)
                        {
                            MainDS.PPerson.DefaultView.RowFilter = PPersonTable.GetPartnerKeyDBName() + "=" + partnerKey.ToString();
                            personRow = (PPersonRow)MainDS.PPerson.DefaultView[0].Row;
                        }

                        POrganisationRow organisationRow = null;

                        if (partnerRow.PartnerClass == MPartnerConstants.PARTNERCLASS_ORGANISATION)
                        {
                            MainDS.POrganisation.DefaultView.RowFilter = POrganisationTable.GetPartnerKeyDBName() + "=" + partnerKey.ToString();
                            organisationRow = (POrganisationRow)MainDS.POrganisation.DefaultView[0].Row;
                        }

                        PUnitRow           unitRow          = null;
                        UmUnitStructureRow unitStructureRow = null;

                        if (partnerRow.PartnerClass == MPartnerConstants.PARTNERCLASS_UNIT)
                        {
                            MainDS.PUnit.DefaultView.RowFilter = PUnitTable.GetPartnerKeyDBName() + "=" + partnerKey.ToString();
                            unitRow = (PUnitRow)MainDS.PUnit.DefaultView[0].Row;
                            MainDS.UmUnitStructure.DefaultView.RowFilter = UmUnitStructureTable.GetChildUnitKeyDBName() + " = " + partnerKey.ToString();

                            long numParents = MainDS.UmUnitStructure.DefaultView.Count;

                            if (numParents == 1)
                            {
                                unitStructureRow = (UmUnitStructureRow)MainDS.UmUnitStructure.DefaultView[0].Row;
                            }
                            else
                            {
                                throw new Exception(
                                          "Units must have exactly one ParentUnit. " +
                                          "The unit with partnerKey " + partnerKey.ToString() + " has " +
                                          numParents.ToString() + ".");
                            }
                        }

                        PBankRow BankRow = null;

                        if (partnerRow.PartnerClass == MPartnerConstants.PARTNERCLASS_BANK)
                        {
                            MainDS.PBank.DefaultView.RowFilter = PBankTable.GetPartnerKeyDBName() + "=" + partnerKey.ToString();
                            BankRow = (PBankRow)MainDS.PBank.DefaultView[0].Row;
                        }

                        partnerCounter++;
                        XmlElement partnerNode = PartnerData.CreateElement("Partner" + partnerCounter.ToString());
                        groupNode.AppendChild(partnerNode);

                        partnerNode.SetAttribute("PartnerKey", partnerRow.PartnerKey.ToString());

                        //groupNode.SetAttribute("ShortName", partnerRow.PartnerShortName.ToString());

                        if (personRow != null)
                        {
                            partnerNode.SetAttribute("FirstName", personRow.FirstName.ToString());
                            partnerNode.SetAttribute("LastName", personRow.FamilyName.ToString());
                            partnerNode.SetAttribute("Title", personRow.Title.ToString());
                        }
                        else if (familyRow != null)
                        {
                            partnerNode.SetAttribute("FirstName", familyRow.FirstName.ToString());
                            partnerNode.SetAttribute("LastName", familyRow.FamilyName.ToString());
                            partnerNode.SetAttribute("Title", familyRow.Title.ToString());
                        }
                        else if (organisationRow != null)
                        {
                            partnerNode.SetAttribute("Name", organisationRow.OrganisationName.ToString());
                        }
                        else if (unitRow != null)
                        {
                            partnerNode.SetAttribute("Name", unitRow.UnitName.ToString());
                            partnerNode.SetAttribute("UnitTypeCode", unitRow.UnitTypeCode.ToString());

                            if (unitStructureRow != null)
                            {
                                partnerNode.SetAttribute("ParentUnitKey", unitStructureRow.ParentUnitKey.ToString());
                            }
                        }

                        if (BankRow != null)
                        {
                            partnerNode.SetAttribute("BranchName", BankRow.BranchName);
                            partnerNode.SetAttribute("BranchCode", BankRow.BranchCode);
                            partnerNode.SetAttribute("BranchBic", BankRow.Bic);
                            partnerNode.SetAttribute("EpFormatFile", BankRow.EpFormatFile);
                        }

                        partnerNode.SetAttribute("CreatedAt", partnerRow.DateCreated.Value.ToString("yyyy-MM-dd HH:mm:ss"));

                        // special types
                        string specialTypes = "";
                        MainDS.PPartnerType.DefaultView.RowFilter = PPartnerTypeTable.GetPartnerKeyDBName() + "=" + partnerKey.ToString();

                        foreach (DataRowView rv in MainDS.PPartnerType.DefaultView)
                        {
                            if (specialTypes.Length > 0)
                            {
                                specialTypes += ", ";
                            }

                            specialTypes += ((PPartnerTypeRow)rv.Row).TypeCode;
                        }

                        if (specialTypes.Length > 0)
                        {
                            partnerNode.SetAttribute("SpecialTypes", specialTypes);
                        }

                        // addresses
                        DataView partnerLocationView = MainDS.PPartnerLocation.DefaultView;
                        partnerLocationView.RowFilter =
                            PPartnerLocationTable.GetPartnerKeyDBName() + " = " + partnerRow.PartnerKey.ToString() +
                            "AND " + PPartnerLocationTable.GetLocationKeyDBName() + " <> 0 "; // ignore invalid addresses
                        Int32 addressCounter = 0;

                        foreach (DataRowView rv in partnerLocationView)
                        {
                            XmlElement addressNode = PartnerData.CreateElement("Address" + (addressCounter > 0 ? addressCounter.ToString() : ""));
                            addressCounter++;
                            partnerNode.AppendChild(addressNode);

                            PPartnerLocationRow partnerLocationRow = (PPartnerLocationRow)rv.Row;

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

                            if (locationView.Count > 0)
                            {
                                PLocationRow locationRow = (PLocationRow)locationView[0].Row;

                                addressNode.SetAttribute("Street", locationRow.StreetName);
                                addressNode.SetAttribute("City", locationRow.City);
                                addressNode.SetAttribute("PostCode", locationRow.PostalCode);
                            }

                            addressNode.SetAttribute("Email", partnerLocationRow.EmailAddress);
                            addressNode.SetAttribute("Phone", partnerLocationRow.TelephoneNumber);
                            addressNode.SetAttribute("MobilePhone", partnerLocationRow.MobileNumber);
                        }

                        // TODO: notes
                        // TODO: This doesn't export as much data as it should?
                    }
                }
            }

            return(TXMLParser.XmlToString(PartnerData));
        }
Example #18
0
        public static string FormatHtmlReceipt(
            String ADonorShortName,
            Int64 ADonorKey,
            TPartnerClass ADonorClass,
            String AGiftCurrency,
            string ALocalCountryCode,
            AGiftTable AGiftsThisDonor,
            string AHTMLTemplateFilename,
            TDBTransaction ATransaction)
        {
            SortedList <string, List <string> > FormValues = new SortedList <string, List <string> >();

            // These are the fields that can be printed in the letter:
            FormValues.Add("AdresseeShortName", new List <string>());
            FormValues.Add("AdresseeTitle", new List <string>());
            FormValues.Add("AdresseeFirstName", new List <string>());
            FormValues.Add("AdresseeFamilyName", new List <string>());
            FormValues.Add("AdresseeStreetAddress", new List <string>());
            FormValues.Add("AdresseeAddress3", new List <string>());
            FormValues.Add("AdresseeCity", new List <string>());
            FormValues.Add("AdresseePostCode", new List <string>());
            FormValues.Add("AdresseeCountry", new List <string>());
            FormValues.Add("FormattedAddress", new List <string>());

            FormValues.Add("DateToday", new List <string>());

            FormValues.Add("DateEntered", new List <string>());
            FormValues.Add("GiftAmount", new List <string>());
            FormValues.Add("GiftCurrency", new List <string>());
            FormValues.Add("GiftTxd", new List <string>());
            FormValues.Add("RecipientShortName", new List <string>());
            FormValues.Add("MotivationDetail", new List <string>());
            FormValues.Add("Reference", new List <string>());
            FormValues.Add("DonorComment", new List <string>());

            FormValues.Add("GiftTotalAmount", new List <string>());
            FormValues.Add("GiftTotalCurrency", new List <string>());
            FormValues.Add("TxdTotal", new List <string>());
            FormValues.Add("NonTxdTotal", new List <string>());


            // Donor Name:
            FormValues["AdresseeShortName"].Add(ADonorShortName);

            if (ADonorClass == TPartnerClass.PERSON)
            {
                PPersonTable Tbl = PPersonAccess.LoadByPrimaryKey(ADonorKey, ATransaction);

                if (Tbl.Rows.Count > 0)
                {
                    FormValues["AdresseeTitle"].Add(Tbl[0].Title);
                    FormValues["AdresseeFirstName"].Add(Tbl[0].FirstName);
                    FormValues["AdresseeFamilyName"].Add(Tbl[0].FamilyName);
                }
            }
            else if (ADonorClass == TPartnerClass.FAMILY)
            {
                PFamilyTable Tbl = PFamilyAccess.LoadByPrimaryKey(ADonorKey, ATransaction);

                if (Tbl.Rows.Count > 0)
                {
                    FormValues["AdresseeTitle"].Add(Tbl[0].Title);
                    FormValues["AdresseeFirstName"].Add(Tbl[0].FirstName);
                    FormValues["AdresseeFamilyName"].Add(Tbl[0].FamilyName);
                }
            }
            else
            {
                FormValues["AdresseeFamilyName"].Add(ADonorShortName);
            }

            FormValues["DateToday"].Add(DateTime.Now.ToString("dd MMMM yyyy"));

            // Donor Adress:
            PLocationTable        Location;
            PPartnerLocationTable PartnerLocation;
            string CountryName;
            string EmailAddress;

            if (TAddressTools.GetBestAddress(ADonorKey, out Location, out PartnerLocation, out CountryName, out EmailAddress, ATransaction))
            {
                PLocationRow LocRow = Location[0];
                FormValues["AdresseeStreetAddress"].Add(LocRow.StreetName);
                FormValues["AdresseeAddress3"].Add(LocRow.Address3);
                FormValues["AdresseeCity"].Add(LocRow.City);
                FormValues["AdresseePostCode"].Add(LocRow.PostalCode);

                if (LocRow.CountryCode != ALocalCountryCode)  // Don't add the Donor's country if it's also my country:
                {
                    FormValues["AdresseeCountry"].Add(CountryName);
                }
                else
                {
                    LocRow.CountryCode = "";
                }

                FormValues["FormattedAddress"].Add(Calculations.DetermineLocationString(LocRow,
                                                                                        Calculations.TPartnerLocationFormatEnum.plfHtmlLineBreak));
            }

            decimal GiftTotal   = 0;
            decimal TxdTotal    = 0;
            decimal NonTxdTotal = 0;

            // Details per gift:
            foreach (AGiftRow GiftRow in AGiftsThisDonor.Rows)
            {
                String           DateEntered   = GiftRow.DateEntered.ToString("dd MMM yyyy");
                String           GiftReference = GiftRow.Reference;
                AGiftDetailTable DetailTbl     = AGiftDetailAccess.LoadViaAGift(
                    GiftRow.LedgerNumber, GiftRow.BatchNumber, GiftRow.GiftTransactionNumber, ATransaction);

                foreach (AGiftDetailRow DetailRow in DetailTbl.Rows)
                {
                    FormValues["Reference"].Add(GiftReference);
                    FormValues["DateEntered"].Add(DateEntered);
                    GiftReference = "";                         // Date and Reference are one-per-gift, not per detail
                    DateEntered   = "";                         // so if this gift has several details, I'll blank the subsequent lines.

                    string DonorComment = "";
                    FormValues["GiftAmount"].Add(StringHelper.FormatUsingCurrencyCode(DetailRow.GiftTransactionAmount, AGiftCurrency));
                    FormValues["GiftCurrency"].Add(AGiftCurrency);
                    FormValues["MotivationDetail"].Add(DetailRow.MotivationDetailCode);
                    GiftTotal += DetailRow.GiftTransactionAmount;

                    if (DetailRow.TaxDeductible)
                    {
                        FormValues["GiftTxd"].Add("Y");
                        TxdTotal += DetailRow.GiftTransactionAmount;
                    }
                    else
                    {
                        FormValues["GiftTxd"].Add(" ");
                        NonTxdTotal += DetailRow.GiftTransactionAmount;
                    }

                    // Recipient Short Name:
                    PPartnerTable RecipientTbl = PPartnerAccess.LoadByPrimaryKey(DetailRow.RecipientKey, ATransaction);

                    if (RecipientTbl.Rows.Count > 0)
                    {
                        String ShortName = Calculations.FormatShortName(RecipientTbl[0].PartnerShortName, eShortNameFormat.eReverseShortname);
                        FormValues["RecipientShortName"].Add(ShortName);
                    }

                    if (DetailRow.CommentOneType == "Donor")
                    {
                        DonorComment += DetailRow.GiftCommentOne;
                    }

                    if (DetailRow.CommentTwoType == "Donor")
                    {
                        if (DonorComment != "")
                        {
                            DonorComment += "\r\n";
                        }

                        DonorComment += DetailRow.GiftCommentTwo;
                    }

                    if (DetailRow.CommentThreeType == "Donor")
                    {
                        if (DonorComment != "")
                        {
                            DonorComment += "\r\n";
                        }

                        DonorComment += DetailRow.GiftCommentThree;
                    }

                    if (DonorComment != "")
                    {
                        DonorComment = "Comment: " + DonorComment;
                    }

                    FormValues["DonorComment"].Add(DonorComment);
                } // foreach GiftDetail
            }     // foreach Gift

            FormValues["GiftTotalAmount"].Add(StringHelper.FormatUsingCurrencyCode(GiftTotal, AGiftCurrency));
            FormValues["GiftTotalCurrency"].Add(AGiftCurrency);
            FormValues["TxdTotal"].Add(StringHelper.FormatUsingCurrencyCode(TxdTotal, AGiftCurrency));
            FormValues["NonTxdTotal"].Add(StringHelper.FormatUsingCurrencyCode(NonTxdTotal, AGiftCurrency));

            return(TFormLettersTools.PrintSimpleHTMLLetter(AHTMLTemplateFilename, FormValues));
        }
Example #19
0
        /// <summary>
        /// Copies over all columns of a Location Row, except the Primary Key columns
        /// and the last four columns (containing creation and change information).
        ///
        /// </summary>
        /// <param name="ACopyLocationsRow">Row to copy data from</param>
        /// <param name="ADestinationLocationsRow">Row to copy data to
        /// </param>
        /// <returns>void</returns>
        public static void CopyLocationData(PLocationRow ACopyLocationsRow, PLocationRow ADestinationLocationsRow)
        {
            ADestinationLocationsRow.Locality = ACopyLocationsRow.Locality;
            ADestinationLocationsRow.StreetName = ACopyLocationsRow.StreetName;
            ADestinationLocationsRow.Address3 = ACopyLocationsRow.Address3;
            ADestinationLocationsRow.City = ACopyLocationsRow.City;
            ADestinationLocationsRow.PostalCode = ACopyLocationsRow.PostalCode;
            ADestinationLocationsRow.County = ACopyLocationsRow.County;
            ADestinationLocationsRow.CountryCode = ACopyLocationsRow.CountryCode;

            // Created/Modified info
            if (!ACopyLocationsRow.IsDateCreatedNull())
            {
                ADestinationLocationsRow.DateCreated = ACopyLocationsRow.DateCreated;
            }

            if (!ACopyLocationsRow.IsDateModifiedNull())
            {
                ADestinationLocationsRow.DateModified = ACopyLocationsRow.DateModified;
            }

            ADestinationLocationsRow.CreatedBy = TSaveConvert.StringColumnToString(((PLocationTable)ACopyLocationsRow.Table).ColumnCreatedBy,
                ACopyLocationsRow);
            ADestinationLocationsRow.ModifiedBy = TSaveConvert.StringColumnToString(((PLocationTable)ACopyLocationsRow.Table).ColumnModifiedBy,
                ACopyLocationsRow);
            ADestinationLocationsRow.ModificationId = ACopyLocationsRow.ModificationId;
        }
Example #20
0
 /// <summary>
 /// </summary>
 /// <param name="AFoundAddressLocationRow"></param>
 /// <param name="ADestinationLocationRow"></param>
 public static void CopyFoundAddressLocationData(PLocationRow AFoundAddressLocationRow, PLocationRow ADestinationLocationRow)
 {
     CopyLocationData(AFoundAddressLocationRow, ADestinationLocationRow);
 }
        private static void GenerateRegistrationOffices(string ACountryName, Int64 APartnerKey, string ACountryCode)
        {
            if (PUnitAccess.Exists(APartnerKey, null))
            {
                TLogging.Log("Office with key " + APartnerKey.ToString() + " already exists.");
                return;
            }

            PartnerEditTDS MainDS = new PartnerEditTDS();

            PPartnerRow partnerRow = MainDS.PPartner.NewRowTyped(true);

            partnerRow.PartnerKey        = APartnerKey;
            partnerRow.PartnerShortName  = ACountryName;
            partnerRow.PartnerClass      = MPartnerConstants.PARTNERCLASS_UNIT;
            partnerRow.StatusCode        = MPartnerConstants.PARTNERSTATUS_ACTIVE;
            partnerRow.AddresseeTypeCode = MPartnerConstants.ADDRESSEETYPE_ORGANISATION;
            MainDS.PPartner.Rows.Add(partnerRow);

            PUnitRow unitRow = MainDS.PUnit.NewRowTyped(true);

            unitRow.PartnerKey   = partnerRow.PartnerKey;
            unitRow.UnitName     = partnerRow.PartnerShortName;
            unitRow.CountryCode  = ACountryCode;
            unitRow.UnitTypeCode = MPartnerConstants.UNIT_TYPE_FIELD;
            MainDS.PUnit.Rows.Add(unitRow);

            PLocationRow locationRow = MainDS.PLocation.NewRowTyped();

            locationRow.SiteKey     = partnerRow.PartnerKey;
            locationRow.LocationKey = 0;
            locationRow.StreetName  = "No valid address on file";
            locationRow.CountryCode = ACountryCode;
            MainDS.PLocation.Rows.Add(locationRow);

            PPartnerLocationRow partnerlocationRow = MainDS.PPartnerLocation.NewRowTyped();

            partnerlocationRow.PartnerKey  = partnerRow.PartnerKey;
            partnerlocationRow.SiteKey     = locationRow.SiteKey;
            partnerlocationRow.LocationKey = locationRow.LocationKey;
            MainDS.PPartnerLocation.Rows.Add(partnerlocationRow);

            PPartnerTypeRow partnertypeRow = MainDS.PPartnerType.NewRowTyped();

            partnertypeRow.PartnerKey = partnerRow.PartnerKey;
            partnertypeRow.TypeCode   = MPartnerConstants.PARTNERTYPE_LEDGER;
            MainDS.PPartnerType.Rows.Add(partnertypeRow);

            UmUnitStructureRow unitStructureRow = MainDS.UmUnitStructure.NewRowTyped();

            unitStructureRow.ParentUnitKey = 1000000;
            unitStructureRow.ChildUnitKey  = partnerRow.PartnerKey;
            MainDS.UmUnitStructure.Rows.Add(unitStructureRow);

            PartnerEditTDSAccess.SubmitChanges(MainDS);

            string sqlInsertModule =
                String.Format("INSERT INTO PUB_{0}({1}, {2}) VALUES ('REG-{3:0000000000}','Registration {4}')",
                              SModuleTable.GetTableDBName(),
                              SModuleTable.GetModuleIdDBName(),
                              SModuleTable.GetModuleNameDBName(),
                              APartnerKey,
                              ACountryName);
            string sqlInsertModulePermissions =
                String.Format("INSERT INTO PUB_{0}({1}, {2}, {3}) VALUES ('DEMO', 'REG-{4:0000000000}',true)",
                              SUserModuleAccessPermissionTable.GetTableDBName(),
                              SUserModuleAccessPermissionTable.GetUserIdDBName(),
                              SUserModuleAccessPermissionTable.GetModuleIdDBName(),
                              SUserModuleAccessPermissionTable.GetCanAccessDBName(),
                              APartnerKey);

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

            try
            {
                DBAccess.GDBAccessObj.ExecuteNonQuery(sqlInsertModule, Transaction);
                DBAccess.GDBAccessObj.ExecuteNonQuery(sqlInsertModulePermissions, Transaction);
                DBAccess.GDBAccessObj.CommitTransaction();
            }
            catch (Exception e)
            {
                TLogging.Log(e.ToString());
                DBAccess.GDBAccessObj.RollbackTransaction();
            }
        }
Example #22
0
        /// <summary>
        /// Determines which address is the 'Best Address' of a Partner, and returns the PLocation record which the
        /// 'Best Address' is pointing to.
        /// </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>
        /// <param name="ALocationDR">PLocation Record that the 'Best Address' is pointing to.</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, out PLocationRow ALocationDR)
        {
            PLocationTable LocationDT;
            TLocationPK BestLocation = new TLocationPK();
            Boolean NewTransaction;

            APartnerLocationDR = null;
            ALocationDR = null;

            BestLocation = DetermineBestAddress(APartnerKey, out APartnerLocationDR);

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

            try
            {
                LocationDT = PLocationAccess.LoadByPrimaryKey(BestLocation.SiteKey, BestLocation.LocationKey, ReadTransaction);

                if (LocationDT.Rows.Count > 0)
                {
                    ALocationDR = LocationDT[0];
                }
            }
            finally
            {
                if (NewTransaction)
                {
                    DBAccess.GDBAccessObj.CommitTransaction();
                    TLogging.LogAtLevel(7, "ServerCalculations.DetermineBestAddress: commited own transaction.");
                }
            }

            return BestLocation;
        }
        /// <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>
        /// Removes a Location from all Extracts that reference it.
        /// It does that by changing these Extract records to reference Location 0
        /// (dummy Location) instead of referencing the Location that is passed in.
        ///
        /// @comment WARNING: must only be called if a Location is deleted
        /// and it is no longer referenced by any other Partner (ie. it will get
        /// deleted from the DB) - this procedure does no check on that!
        ///
        /// </summary>
        /// <param name="ALocationRow">Location DataRow which should be processed</param>
        /// <param name="ASubmitChangesTransaction">Running transaction in which the DB commands
        /// will be enlisted</param>
        private static void RemoveLocationFromExtracts(PLocationRow ALocationRow,
            TDBTransaction ASubmitChangesTransaction)
        {
            MExtractTable ExtractsDT;
            Int32 Counter;
            StringCollection RequiredColumns;

//          TLogging.LogAtLevel(9, "RemoveLocationFromExtracts for Location " +
//              Convert.ToInt32(ALocationRow[MExtractTable.GetLocationKeyDBName(), DataRowVersion.Original]).ToString());
            Counter = 0;

            // Load all Extracts that contain the Location
            RequiredColumns = new StringCollection();
            RequiredColumns.Add(MExtractTable.GetExtractIdDBName());
            RequiredColumns.Add(MExtractTable.GetPartnerKeyDBName());
            RequiredColumns.Add(MExtractTable.GetSiteKeyDBName());
            RequiredColumns.Add(MExtractTable.GetLocationKeyDBName());
            ExtractsDT = MExtractAccess.LoadViaPLocation(Convert.ToInt64(
                    ALocationRow[MExtractTable.GetSiteKeyDBName(),
                                 DataRowVersion.Original]), Convert.ToInt32(
                    ALocationRow[MExtractTable.GetLocationKeyDBName(), DataRowVersion.Original]), RequiredColumns, ASubmitChangesTransaction);

            if (ExtractsDT.Rows.Count != 0)
            {
                /*
                 * Change these Extract records to reference Location 0 (dummy Location)
                 * instead of referencing the current Location.
                 */
                while (Counter != ExtractsDT.Rows.Count)
                {
//                  TLogging.LogAtLevel(8,  "RemoveLocationFromExtracts: Removing Location with LocationKey " + ExtractsDT[Counter].LocationKey.ToString() +
//                       " from Extract with ExtractID ''" + ExtractsDT[Counter].ExtractId.ToString() + "''.");
                    ExtractsDT[Counter].SiteKey = 0;
                    ExtractsDT[Counter].LocationKey = 0;
                    Counter = Counter + 1;
                }

                // Submit the changes to these Extract records to the DB
                MExtractAccess.SubmitChanges(ExtractsDT, ASubmitChangesTransaction);
            }
            else
            {
//              TLogging.LogAtLevel(9, "RemoveLocationFromExtracts: Location with LocationKey " +
//                  ALocationRow[MExtractTable.GetLocationKeyDBName(), DataRowVersion.Original].ToString() + " was not referenced in any Extract -> nothing to do.");
            }
        }
Example #25
0
        /// <summary>
        /// Determines which address is the 'Best Address' of a Partner, and returns the PLocation record which the
        /// 'Best Address' is pointing to.
        /// </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="ALocationDR">PLocation Record that the 'Best Address' is pointing to.</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 PLocationRow ALocationDR)
        {
            TLocationPK BestLocation = new TLocationPK();
            PPartnerLocationRow Tmp;

            ALocationDR = null;

            BestLocation = DetermineBestAddress(APartnerKey, out Tmp, out ALocationDR);

            return BestLocation;
        }
        /// <summary>
        /// </summary>
        /// <param name="ALocationRow"></param>
        /// <returns></returns>
        private static Boolean CheckHasLocationChanged(PLocationRow ALocationRow)
        {
            Boolean ReturnValue;

            ReturnValue = false;

            // We only check Modified DataRows here
            if (ALocationRow.RowState == DataRowState.Modified)
            {
                // Check if any of the Addressholding fields were changed
                if (!SameValueOriginalCurrent(ALocationRow, PLocationTable.GetLocalityDBName())
                    || !SameValueOriginalCurrent(ALocationRow, PLocationTable.GetStreetNameDBName())
                    || !SameValueOriginalCurrent(ALocationRow, PLocationTable.GetAddress3DBName())
                    || !SameValueOriginalCurrent(ALocationRow, PLocationTable.GetCityDBName())
                    || !SameValueOriginalCurrent(ALocationRow, PLocationTable.GetCountyDBName())
                    || !SameValueOriginalCurrent(ALocationRow, PLocationTable.GetCountryCodeDBName())
                    || !SameValueOriginalCurrent(ALocationRow, PLocationTable.GetPostalCodeDBName()))
                {
                    ReturnValue = true;
//                  TLogging.LogAtLevel(9, "CheckHasLocationChanged: Location has changed.");
                }
                else
                {
//                  TLogging.LogAtLevel(9, "CheckHasLocationChanged: Location has NOT changed.");
                }
            }

            return ReturnValue;
        }
        /// <summary>
        /// Builds a formatted String out of the data that is contained in a Location.
        /// </summary>
        /// <param name="ALocationDR">DataRow containing the Location data.</param>
        /// <param name="APartnerLocationStringFormat">Specifies how to format the String that is returned.</param>
        /// <param name="AaddressOrder">AddressOrder from PCountry row</param>
        /// <param name="ACountryName">If this is blank, the PLocationRow CountryCode will be used.</param>
        /// <returns>Formatted String.</returns>
        public static String DetermineLocationString(PLocationRow ALocationDR,
            TPartnerLocationFormatEnum APartnerLocationStringFormat = TPartnerLocationFormatEnum.plfLineBreakSeparated,
            Int32 AaddressOrder = 0,
            String ACountryName = "")
        {
            if (ACountryName == "")
            {
                ACountryName = ALocationDR.CountryCode;
            }

            return DetermineLocationString(ALocationDR.Building1,
                ALocationDR.Building2,
                ALocationDR.Locality,
                ALocationDR.StreetName,
                ALocationDR.Address3,
                ALocationDR.Suburb,
                ALocationDR.City,
                ALocationDR.County,
                ALocationDR.PostalCode,
                ACountryName,
                APartnerLocationStringFormat,
                AaddressOrder);
        }
        private void ApplyText(String AOtherFormTitle, String AOtherExplanation, PLocationRow ALocationRow)
        {
            PLocationTable LocationDT;

            if (AOtherExplanation != "")
            {
                lblExplainPartnerList1.Text = AOtherExplanation;
            }
            else
            {
                lblExplainPartnerList1.Text = Catalog.GetString("The following Partners also use this Partner's address.");
            }

            if (AOtherFormTitle != "")
            {
                this.Text = AOtherFormTitle;
            }
            else
            {
                this.Text = Catalog.GetString("Change Location for selected Partners");
            }

            /* Set up address lines display */
            LocationDT = (PLocationTable)ALocationRow.Table;
            txtChangedAddress.Text =
                TSaveConvert.StringColumnToString(LocationDT.ColumnLocality, ALocationRow) + "\r\n" + TSaveConvert.StringColumnToString(
                    LocationDT.ColumnStreetName,
                    ALocationRow) + "\r\n" +
                TSaveConvert.StringColumnToString(LocationDT.ColumnAddress3, ALocationRow) + "\r\n" + TSaveConvert.StringColumnToString(
                    LocationDT.ColumnCity,
                    ALocationRow) + ' ' +
                TSaveConvert.StringColumnToString(LocationDT.ColumnPostalCode, ALocationRow) + "\r\n" + TSaveConvert.StringColumnToString(
                    LocationDT.ColumnCounty,
                    ALocationRow) + ' ' + TSaveConvert.StringColumnToString(LocationDT.ColumnCountryCode, ALocationRow);
        }
Example #29
0
        private static PartnerDetails GetDonor(Int64 APartnerKey)
        {
            if (DonorList.ContainsKey(APartnerKey))
            {
                return(DonorList[APartnerKey]);
            }

            PartnerDetails Ret        = new PartnerDetails();
            PPartnerTable  PartnerTbl = PPartnerAccess.LoadByPrimaryKey(APartnerKey, FTransaction);

            if (PartnerTbl.Rows.Count > 0)
            {
                PPartnerRow PartnerRow = PartnerTbl[0];

                Ret.LastName  = PartnerRow.PartnerShortName;
                Ret.Anonymous = PartnerRow.AnonymousDonor;

                if (PartnerRow.PartnerClass == "PERSON")
                {
                    PPersonTable PersonTbl = PPersonAccess.LoadByPrimaryKey(APartnerKey, FTransaction);

                    if (PersonTbl.Rows.Count > 0)
                    {
                        PPersonRow PersonRow = PersonTbl[0];
                        Ret.FirstName = PersonRow.FirstName;
                        Ret.LastName  = PersonRow.FamilyName;
                        Ret.Class     = "PERSON";
                    }
                }

                if (PartnerRow.PartnerClass == "FAMILY")
                {
                    PFamilyTable FamilyTbl = PFamilyAccess.LoadByPrimaryKey(APartnerKey, FTransaction);

                    if (FamilyTbl.Rows.Count > 0)
                    {
                        PFamilyRow FamilyRow = FamilyTbl[0];
                        Ret.FirstName = FamilyRow.FirstName;
                        Ret.LastName  = FamilyRow.FamilyName;
                        Ret.Class     = "FAMILY";
                    }
                }

                PPartnerLocationRow PartnerLocationRow;
                TLocationPK         LocationKey = ServerCalculations.DetermineBestAddress(APartnerKey, out PartnerLocationRow);

                if (LocationKey.LocationKey != -1)
                {
                    Ret.Email     = PartnerLocationRow.EmailAddress;
                    Ret.Telephone = PartnerLocationRow.TelephoneNumber;
                    PLocationTable LocationTbl = PLocationAccess.LoadByPrimaryKey(PartnerLocationRow.SiteKey,
                                                                                  PartnerLocationRow.LocationKey,
                                                                                  FTransaction);

                    if (LocationTbl.Rows.Count > 0)
                    {
                        PLocationRow LocationRow = LocationTbl[0];
                        Ret.Address = Calculations.DetermineLocationString(LocationRow, Calculations.TPartnerLocationFormatEnum.plfCommaSeparated);
                    }
                }
            }

            DonorList.Add(APartnerKey, Ret);
            return(Ret);
        }