private static string ConcatPartnerAttributes(PPartnerAttributeRow row)
 {
     return(row.PartnerKey.ToString() + ";" +
            row.AttributeType + ";" +
            row.Value + ";" +
            row.Current);
 }
 private static string ConcatPartnerAttributes(PPartnerAttributeRow row)
 {
     return row.PartnerKey.ToString() + ";" +
            row.AttributeType + ";" +
            row.Value + ";" +
            row.Current;
 }
        /// <summary>
        /// Checks whether Partner Attributes of the same Attribute Type exist in the database.
        /// </summary>
        /// <param name="AImportedPartnerAttribRow"><see cref="PPartnerAttributeRow" /> that holds the imported data.</param>
        /// <param name="AFoundPartnerAttribDR"><see cref="PPartnerAttributeRow" /> that holds the record that was found -
        /// if one was found, otherwise this is null.</param>
        /// <param name="ATransaction">Instantiated DB Transaction.</param>
        /// <returns>False if the row should be imported as found in the import file, otherwise true.</returns>
        public bool ExistingPartnerAttributes(PPartnerAttributeRow AImportedPartnerAttribRow,
                                              out PPartnerAttributeRow AFoundPartnerAttribDR, TDBTransaction ATransaction)
        {
            PPartnerAttributeTable ExistingPartnerAttributeDT;

            AFoundPartnerAttribDR = null;

            // Find existing Partner Attribute(s) of the same AttributeType (ignoring sequence!)
            PPartnerAttributeRow TmpPartnerAttributeRow = new PPartnerAttributeTable().NewRowTyped(false);

            TmpPartnerAttributeRow.PartnerKey    = AImportedPartnerAttribRow.PartnerKey;
            TmpPartnerAttributeRow.AttributeType = AImportedPartnerAttribRow.AttributeType;

            ExistingPartnerAttributeDT = PartnerAttributeLoadUsingTemplate(TmpPartnerAttributeRow, null, ATransaction);

            if (ExistingPartnerAttributeDT.Count == 0)
            {
                // No existing Partner Attribute(s) of the same AttributeType -->
                // we want to import the row as found in the import file!
                return(false);
            }

            // Existing Partner Attribute(s) of the same AttributeType --> Check to see whether we want to import
            // that Row, or whether we want to overwrite an existing Row with some imported data!
            for (int Counter = 0; Counter < ExistingPartnerAttributeDT.Rows.Count; Counter++)
            {
                if (ExistingPartnerAttributeDT[Counter].Value == AImportedPartnerAttribRow.Value)
                {
                    // This *is* the same Partner Attribute!
                    AFoundPartnerAttribDR = ExistingPartnerAttributeDT[Counter];

                    break;
                }
                else if (AImportedPartnerAttribRow.AttributeType == Ict.Petra.Shared.MPartner.Calculations.ATTR_TYPE_PARTNERS_PRIMARY_CONTACT_METHOD)
                {
                    // This *is* the same Partner Attribute!
                    AFoundPartnerAttribDR = ExistingPartnerAttributeDT[Counter];

                    break;
                }
            }

            if (AFoundPartnerAttribDR != null)
            {
                // Same Partner Attribute --> overwrite the Row that is existing in the DB with some imported data!
                return(true);
            }

            // No existing Partner Attribute(s) of the same AttributeType with the same Value -->
            // we want to import the row as found in the import file!
            return(false);
        }
Beispiel #4
0
        /// <summary>
        /// Gets additional mobile or landline numbers that are not the primary phone number.
        /// </summary>
        /// <param name="AReadTransaction"></param>
        /// <param name="APartnerKey">A partner key for which we are finding the additional information.</param>
        /// <param name="AMobileNumbers">Additional mobile numbers for the specified partner.  Empty string if none.</param>
        /// <param name="AAlternatePhoneNumbers">Additional landline numbers for the specified partner.  Empty string if none.</param>
        public static void GetPartnersAdditionalPhoneNumbers(
            TDBTransaction AReadTransaction,
            Int64 APartnerKey, out string AMobileNumbers, out string AAlternatePhoneNumbers)
        {
            AMobileNumbers         = string.Empty;
            AAlternatePhoneNumbers = string.Empty;

            // Get all the contact details for the specified partner and then find the ones that relate to phones
            PPartnerAttributeTable partnerAttributeDT = GetPartnersContactDetailAttributes(APartnerKey);
            DataView allPhoneNumbers = Calculations.DeterminePartnerPhoneNumbers(AReadTransaction, partnerAttributeDT, true, false);

            foreach (DataRowView rv in allPhoneNumbers)
            {
                // Evaluate each row in turn
                PPartnerAttributeRow row = (PPartnerAttributeRow)rv.Row;

                if (row.NoLongerCurrentFrom != null)
                {
                    if (row.NoLongerCurrentFrom < DateTime.Today)
                    {
                        continue;
                    }
                }

                if (row.AttributeType == MPartnerConstants.ATTR_TYPE_MOBILE_PHONE)
                {
                    if (row.Primary == false)
                    {
                        string number = Calculations.ConcatenatePhoneOrFaxNumberWithIntlCountryPrefix(row);
                        AMobileNumbers += (AMobileNumbers.Length > 0) ? "; " : string.Empty;
                        AMobileNumbers += number;
                    }
                }
                else if (row.AttributeType == MPartnerConstants.ATTR_TYPE_PHONE)
                {
                    if (row.Primary == false)
                    {
                        string number = Calculations.ConcatenatePhoneOrFaxNumberWithIntlCountryPrefix(row);
                        AAlternatePhoneNumbers += (AAlternatePhoneNumbers.Length > 0) ? "; " : string.Empty;
                        AAlternatePhoneNumbers += number;
                    }
                }
            }
        }
        /// <summary>
        /// Takes an PPartnerAttribute Row from the DB and modifies it with data from a PPartnerAttribute Row that got
        /// populated from imported data.
        /// </summary>
        /// <param name="AImportedPartnerAttributeDR">PPartnerAttribute Row that got populated from imported data.</param>
        /// <param name="AExistingPartnerAttributeDR">PPartnerAttribute Row from the DB.</param>
        public void TakeExistingPartnerAttributeRecordAndModifyIt(PPartnerAttributeRow AImportedPartnerAttributeDR,
                                                                  PPartnerAttributeRow AExistingPartnerAttributeDR)
        {
            // First step: Store some details of the to-be-imported record in Variables
            var ImportDRValue               = AImportedPartnerAttributeDR.Value; // only needed for Attribute Type 'PARTNERS_PRIMARY_CONTACT_METHOD'
            var ImportDRComment             = AImportedPartnerAttributeDR.Comment;
            var ImportDRPrimary             = AImportedPartnerAttributeDR.Primary;
            var ImportDRWithinOrganisation  = AImportedPartnerAttributeDR.WithinOrganisation;
            var ImportDRSpecialised         = AImportedPartnerAttributeDR.Specialised;
            var ImportDRConfidential        = AImportedPartnerAttributeDR.Confidential;
            var ImportDRCurrent             = AImportedPartnerAttributeDR.Current;
            var ImportDRNoLongerCurrentFrom = AImportedPartnerAttributeDR.NoLongerCurrentFrom;

            // Second step: Copy all data from the record as it exists in the DB over into the to-be-imported record.
            // This is necessary so that the overwriting of some details of the record (see below) creates DataColumns
            // whose 'Modified' data is different than their 'Current' data (otherwise an 'empty' UPDATE command will
            // be issued against the DB!)
            DataUtilities.CopyAllColumnValues(AExistingPartnerAttributeDR, AImportedPartnerAttributeDR);

            // Make sure the Imported DataRows' DataRowState is no longer 'Added' as we don't want to add it to the
            // database, but want to update the existing row in the database!
            // (All the DataColumns hold 'Current' Data after this!)
            AImportedPartnerAttributeDR.AcceptChanges();

            // Third step: Overwrite some details of the record as it exists in the DB with details of the
            // to-be-imported record. (All these DataColumns will hold 'Modified' Data after this!)
            AImportedPartnerAttributeDR.Value               = ImportDRValue; // only needed for Attribute Type 'PARTNERS_PRIMARY_CONTACT_METHOD'
            AImportedPartnerAttributeDR.Comment             = ImportDRComment;
            AImportedPartnerAttributeDR.Primary             = ImportDRPrimary;
            AImportedPartnerAttributeDR.WithinOrganisation  = ImportDRWithinOrganisation;
            AImportedPartnerAttributeDR.Specialised         = ImportDRSpecialised;
            AImportedPartnerAttributeDR.Confidential        = ImportDRConfidential;
            AImportedPartnerAttributeDR.Current             = ImportDRCurrent;
            AImportedPartnerAttributeDR.NoLongerCurrentFrom = ImportDRNoLongerCurrentFrom;

            // Note: The DataRows' DataRowState is now 'Modified', and that causes the DB Access layer to issue an
            // UPDATE statement later. That statement will update data in each of the DB Tables' columns where a
            // DataColumn holds different data in the 'Current' and 'Modified' versions of a DataColum, i.e. where
            // there is a real difference between the to-be-imported data and the data in the record that is already
            // in the DB.
        }
Beispiel #6
0
        /// <summary>
        /// Creates a PPartnerAttribute Record out of data that is held in a data structure that is a p_parnter_attribute
        /// representation.
        /// </summary>
        /// <param name="APPARec">Data structure that is p_parnter_attribute representation.</param>
        /// <param name="AMainDS">DataSet to which the PPartnerAttribute Record should be added to.</param>
        public static void CreatePartnerContactDetailRecord(TPartnerContactDetails.PPartnerAttributeRecord APPARec,
                                                            DataSet AMainDS)
        {
            var MainDS = (PartnerImportExportTDS)AMainDS;

            PPartnerAttributeRow PartnerAttributeDR = MainDS.PPartnerAttribute.NewRowTyped(false);

            PartnerAttributeDR.PartnerKey          = APPARec.PartnerKey;
            PartnerAttributeDR.Sequence            = (Int32)SequenceGetter(TSequenceNames.seq_partner_attribute_index);
            PartnerAttributeDR.AttributeType       = APPARec.AttributeType;
            PartnerAttributeDR.Index               = APPARec.Index;
            PartnerAttributeDR.Value               = APPARec.Value;
            PartnerAttributeDR.Comment             = APPARec.Comment;
            PartnerAttributeDR.Primary             = APPARec.Primary;
            PartnerAttributeDR.WithinOrganisation  = APPARec.WithinOrganisation;
            PartnerAttributeDR.Specialised         = APPARec.Specialised;
            PartnerAttributeDR.Confidential        = APPARec.Confidential;
            PartnerAttributeDR.Current             = APPARec.Current;
            PartnerAttributeDR.NoLongerCurrentFrom = APPARec.NoLongerCurrentFrom;

            MainDS.PPartnerAttribute.Rows.Add(PartnerAttributeDR);
        }
        /// <summary>
        /// Creates a PPartnerAttribute Record out of data that is held in a data structure that is a p_partner_attribute
        /// representation.
        /// </summary>
        /// <param name="APPARec">Data structure that is p_partner_attribute representation.</param>
        /// <param name="AMainDS">DataSet to which the PPartnerAttribute Record should be added to.</param>
        /// <param name="ADataBase"></param>
        public void CreatePartnerContactDetailRecord(PPartnerAttributeRecord APPARec,
                                                     DataSet AMainDS, TDataBase ADataBase = null)
        {
            var MainDS = (PartnerImportExportTDS)AMainDS;

            PPartnerAttributeRow PartnerAttributeDR = MainDS.PPartnerAttribute.NewRowTyped(false);

            TDataBase      db          = DBAccess.Connect("CreatePartnerContactDetailRecord", ADataBase);
            TDBTransaction Transaction = new TDBTransaction();

            PartnerAttributeDR.PartnerKey = APPARec.PartnerKey;

            bool SubmitOK = false;

            db.WriteTransaction(ref Transaction,
                                ref SubmitOK,
                                delegate
            {
                PartnerAttributeDR.Sequence = Convert.ToInt32(db.GetNextSequenceValue(TSequenceNames.seq_partner_attribute_index.ToString(), Transaction));
                SubmitOK = true;
            });

            PartnerAttributeDR.AttributeType       = APPARec.AttributeType;
            PartnerAttributeDR.Index               = APPARec.Index;
            PartnerAttributeDR.Value               = APPARec.Value;
            PartnerAttributeDR.ValueCountry        = APPARec.ValueCountry;
            PartnerAttributeDR.Comment             = APPARec.Comment;
            PartnerAttributeDR.Primary             = APPARec.Primary;
            PartnerAttributeDR.WithinOrganisation  = APPARec.WithinOrganisation;
            PartnerAttributeDR.Specialised         = APPARec.Specialised;
            PartnerAttributeDR.Confidential        = APPARec.Confidential;
            PartnerAttributeDR.Current             = APPARec.Current;
            PartnerAttributeDR.NoLongerCurrentFrom = APPARec.NoLongerCurrentFrom;

            MainDS.PPartnerAttribute.Rows.Add(PartnerAttributeDR);
        }
        /// Upgrade to version 2015-01
        public static bool UpgradeDatabase201412_201501()
        {
            // There are no new tables and fields

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

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

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

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

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

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

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

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

                    DataTable PPartnersLocationsDT = GetNewPPartnerLocationTableInstance();

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

                    TLocationPK bestAddress = Calculations.DetermineBestAddress(PPartnersLocationsDT);

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

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

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

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

                            AttributeConcatenated = ConcatPartnerAttributes(partnerattribute);

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

                            partnerlocation.SetEmailAddressNull();
                        }

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

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

                            AttributeConcatenated = ConcatPartnerAttributes(partnerattribute);

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

                            partnerlocation.SetTelephoneNumberNull();
                        }

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

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

                            AttributeConcatenated = ConcatPartnerAttributes(partnerattribute);

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

                            partnerlocation.SetFaxNumberNull();
                        }

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

                            AttributeConcatenated = ConcatPartnerAttributes(partnerattribute);

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

                            partnerlocation.SetAlternateTelephoneNull();
                        }

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

                            AttributeConcatenated = ConcatPartnerAttributes(partnerattribute);

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

                            partnerlocation.SetMobileNumberNull();
                        }

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

                            AttributeConcatenated = ConcatPartnerAttributes(partnerattribute);

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

                            partnerlocation.SetUrlNull();
                        }
                    }
                }

                PPartnerLocationAccess.SubmitChanges(partnerlocations, SubmitChangesTransaction);
                PPartnerAttributeAccess.SubmitChanges(partnerattributes, SubmitChangesTransaction);
                SubmissionResult = TSubmitChangesResult.scrOK;
            });
            return(true);
        }
        private void ShowDetailsManual(PPartnerAttributeRow ARow)
        {
//            long RelationPartnerKey;

            // show controls if not visible yet
            MakeDetailsInvisible(false);

            btnDelete.Enabled = false;

            if (ARow != null)
            {
                btnDelete.Enabled = true;
            }

            OnContactTypeChanged(null, null);

            FRunningInsideShowDetails = false;
        }
Beispiel #10
0
        public static bool SavePartner(PartnerEditTDS AMainDS,
                                       List <string> ASubscriptions,
                                       List <string> APartnerTypes,
                                       bool ASendMail,
                                       string ADefaultEmailAddress,
                                       string ADefaultPhoneMobile,
                                       string ADefaultPhoneLandline,
                                       out TVerificationResultCollection AVerificationResult)
        {
            List <string>  Dummy1, Dummy2;
            string         Dummy3, Dummy4, Dummy5;
            PartnerEditTDS SaveDS;

            AVerificationResult = new TVerificationResultCollection();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            try
            {
                TSubmitChangesResult result = uiconnector.SubmitChanges(
                    ref SaveDS,
                    ref ResponseDS,
                    out AVerificationResult);
                return(result == TSubmitChangesResult.scrOK);
            }
            catch (Exception e)
            {
                TLogging.Log(e.ToString());
                AVerificationResult.Add(new TVerificationResult("error", e.Message, TResultSeverity.Resv_Critical));
                return(false);
            }
        }
        /// <summary>
        /// Validates the Partner Edit screens' Contact Details Tab data.
        /// </summary>
        /// <param name="AContext">Context that describes where the data validation failed.</param>
        /// <param name="ARow">The <see cref="DataRow" /> which holds the the data against which the validation is run.</param>
        /// <param name="AVerificationResultCollection">Will be filled with any <see cref="TVerificationResult" /> items if
        /// data validation errors occur.</param>
        /// <param name="AValidationControlsDict">A <see cref="TValidationControlsDict" /> containing the Controls that
        /// display data that is about to be validated.</param>
        /// <param name="AValueKind">The PPartnerAttributeType.AttributeValueKind of the DataRow passed in in <paramref name="ARow"/>.</param>
        public static void ValidateContactDetailsManual(object AContext, PPartnerAttributeRow ARow,
            ref TVerificationResultCollection AVerificationResultCollection, TValidationControlsDict AValidationControlsDict,
            TPartnerAttributeTypeValueKind AValueKind)
        {
            DataColumn ValidationColumn;
            TValidationControlsData ValidationControlsData;
            TVerificationResult VerificationResult = null;

            // Don't validate deleted DataRows
            if (ARow.RowState == DataRowState.Deleted)
            {
                return;
            }

            // 'Value' must not be null
            ValidationColumn = ARow.Table.Columns[PPartnerAttributeTable.ColumnValueId];

            if (AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData))
            {
                VerificationResult = TGeneralChecks.ValueMustNotBeNullOrEmptyString(ARow.Value,
                    ValidationControlsData.ValidationControlLabel,
                    AContext, ValidationColumn, ValidationControlsData.ValidationControl);

                // Handle addition to/removal from TVerificationResultCollection
                AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, VerificationResult, ValidationColumn);
            }

            // If this record is about an E-Mail Contact Detail...
            if (AValueKind == TPartnerAttributeTypeValueKind.CONTACTDETAIL_EMAILADDRESS)
            {
                // ...then the E-mail Address must be in a correct format
                ValidationColumn = ARow.Table.Columns[PPartnerAttributeTable.ColumnValueId];

                if (AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData))
                {
                    VerificationResult = TStringChecks.ValidateEmail(ARow.Value, true,
                        AContext, ValidationColumn, ValidationControlsData.ValidationControl);

                    // Handle addition to/removal from TVerificationResultCollection
                    AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, VerificationResult, ValidationColumn);
                }
            }

            // 'No Longer Current From Date' must not be a future date if the 'Current' Flag is set to false
            ValidationColumn = ARow.Table.Columns[PPartnerAttributeTable.ColumnNoLongerCurrentFromId];

            if (AValidationControlsDict.TryGetValue(ValidationColumn, out ValidationControlsData))
            {
                VerificationResult = null;

                if (!ARow.Current)
                {
                    VerificationResult = TDateChecks.IsCurrentOrPastDate(ARow.NoLongerCurrentFrom,
                        ValidationControlsData.ValidationControlLabel, AContext, ValidationColumn,
                        ValidationControlsData.ValidationControl);
                }

                // Handle addition to/removal from TVerificationResultCollection
                AVerificationResultCollection.Auto_Add_Or_AddOrRemove(AContext, VerificationResult, ValidationColumn);
            }
        }
        /// <summary>
        /// Deletes the current row and optionally populates a completion message
        /// </summary>
        /// <param name="ARowToDelete">the currently selected row to delete</param>
        /// <param name="ACompletionMessage">if specified, is the deletion completion message</param>
        /// <returns>true if row deletion is successful</returns>
        private bool DeleteRowManual(PPartnerAttributeRow ARowToDelete, ref string ACompletionMessage)
        {
            bool deletionSuccessful = false;

            // no message to be shown after deletion
            ACompletionMessage = "";

            try
            {
                ARowToDelete.Delete();
                deletionSuccessful = true;
            }
            catch (Exception ex)
            {
                ACompletionMessage = ex.Message;
                MessageBox.Show(ex.Message,
                    "Deletion Error",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
            }

            return deletionSuccessful;
        }
        /// <summary>
        /// Code to be run after the deletion process,
        /// </summary>
        /// <param name="ARowToDelete">the row that was/was to be deleted,</param>
        /// <param name="AAllowDeletion">whether or not the user was permitted to delete,</param>
        /// <param name="ADeletionPerformed">whether or not the deletion was performed successfully,</param>
        /// <param name="ACompletionMessage">if specified, is the deletion completion message,</param>
        private void PostDeleteManual(PPartnerAttributeRow ARowToDelete,
            bool AAllowDeletion,
            bool ADeletionPerformed,
            string ACompletionMessage)
        {
            bool NoEmailAddressesAvailableAnymore = false;
            bool NoPhoneNumbersAvailableAnymore = false;
            string PrimEmailConsequence = StrEmailUnavailableConsequenceSelectNewOne;
            string PrimEmailMessageBoxTitle = String.Format(StrEmailUnavailableConsequenceSelectNewOneTitle, StrPrimaryEmail);
            string PrimPhoneConsequence = StrPhoneUnavailableConsequenceSelectNewOne;
            string PrimPhoneMessageBoxTitle = String.Format(StrPhoneUnavailableConsequenceSelectNewOneTitle, StrPrimaryPhone);

            if (ADeletionPerformed)
            {
                StringCollection EmailAttrColl = StringHelper.StrSplit(
                    TSharedDataCache.TMPartner.GetEmailPartnerAttributesConcatStr(), ", ");

                if (EmailAttrColl.Contains("'" + FDeletedRowsAttributeType + "'"))
                {
                    // User deleted an E-mail Contact Detail

                    if (cmbPrimaryEMail.GetSelectedString(-1) == FDeletedRowsValue)
                    {
                        DataView EligibleEmailAddrsDV = Calculations.DeterminePartnerEmailAddresses(
                            FMainDS.PPartnerAttribute, true);

                        if (EligibleEmailAddrsDV.Count == 0)
                        {
                            NoEmailAddressesAvailableAnymore = true;
                            PrimEmailConsequence = String.Format(StrEmailUnavailableConsequenceCleared, StrPrimaryEmail);
                            PrimEmailMessageBoxTitle = String.Format(StrEmailUnavailableConsequenceClearedTitle, StrPrimaryEmail);
                        }

                        // User deleted the E-mail Contact Detail that was set as the 'Primary E-Mail Address':
                        // Refresh all E-Mail Address Combos (which upon that will no longer contain the E-mail
                        // Address of the deleted Contact Detail!) and notify the user that (s)he needs to take action.
                        UpdateEmailComboItemsOfAllEmailCombos(true);

                        MessageBox.Show(
                            String.Format(
                                Catalog.GetString("You have deleted the Contact Detail that was set as the 'Primary E-Mail Address'.\r\n\r\n{0}"),
                                PrimEmailConsequence),
                            PrimEmailMessageBoxTitle,
                            MessageBoxButtons.OK, MessageBoxIcon.Warning);

                        if (!NoEmailAddressesAvailableAnymore)
                        {
                            // Show the other current e-mail-Address(es) to the user
                            cmbPrimaryEMail.DroppedDown = true;
                        }
                    }
                    else
                    {
                        // User deleted a E-mail Contact Detail that was not set as the 'Primary E-Mail Address':
                        // Simply refresh all E-Mail Address Combos.
                        UpdateEmailComboItemsOfAllEmailCombos(true);
                    }
                }

                StringCollection PhoneAttrColl = StringHelper.StrSplit(
                    TSharedDataCache.TMPartner.GetPhonePartnerAttributesConcatStr(), ", ");

                if (PhoneAttrColl.Contains("'" + FDeletedRowsAttributeType + "'"))
                {
                    // User deleted a Phone Contact Detail

                    if (cmbPrimaryPhoneForContacting.GetSelectedString(-1) == FDeletedRowsValue)
                    {
                        DataView EligiblePhoneNrsDV = Calculations.DeterminePartnerPhoneNumbers(FMainDS.PPartnerAttribute,
                            true, false);

                        if (EligiblePhoneNrsDV.Count == 0)
                        {
                            NoPhoneNumbersAvailableAnymore = true;
                            PrimPhoneConsequence = String.Format(StrPhoneUnavailableConsequenceCleared, StrPrimaryPhone);
                            PrimPhoneMessageBoxTitle = String.Format(StrPhoneUnavailableConsequenceClearedTitle, StrPrimaryPhone);
                        }

                        // User deleted the Phone Contact Detail that was set as the 'Primary Phone':
                        // Refresh all Phone Combos (which upon that will no longer contain the Phone
                        // Number of the deleted Contact Detail!) and notify the user that (s)he needs to take action.
                        UpdatePhoneComboItemsOfAllPhoneCombos();

                        MessageBox.Show(
                            String.Format(
                                Catalog.GetString("You have deleted the Contact Detail that was set as the 'Primary Phone'.\r\n\r\n{0}"),
                                PrimPhoneConsequence),
                            PrimPhoneMessageBoxTitle,
                            MessageBoxButtons.OK, MessageBoxIcon.Warning);

                        if (!NoPhoneNumbersAvailableAnymore)
                        {
                            // Show the other current Phone Number(s) to the user
                            cmbPrimaryPhoneForContacting.DroppedDown = true;
                        }
                    }
                    else
                    {
                        // User deleted a Phone Contact Detail that was not set as the 'Primary Phone':
                        // Simply refresh all Phone Combos.
                        UpdatePhoneComboItemsOfAllPhoneCombos();
                    }
                }

                DoRecalculateScreenParts();

                if (grdDetails.Rows.Count <= 1)
                {
                    // hide details part and disable buttons if no record in grid (first row for headings)
                    btnDelete.Enabled = false;
                    pnlDetails.Visible = false;
                }
            }

            FDeletedRowsAttributeType = String.Empty;
            FDeletedRowsValue = String.Empty;
        }
 private void GetDetailDataFromControlsManual(PPartnerAttributeRow ARow)
 {
 }
        /// <summary>
        /// Performs checks to determine whether a deletion of the current
        ///  row is permissable
        /// </summary>
        /// <param name="ARowToDelete">the currently selected row to be deleted</param>
        /// <param name="ADeletionQuestion">can be changed to a context-sensitive deletion confirmation question</param>
        /// <returns>true if user is permitted and able to delete the current row</returns>
        private bool PreDeleteManual(PPartnerAttributeRow ARowToDelete, ref string ADeletionQuestion)
        {
            // Those values are getting safed for use in the PostDeleteManual Method
            // Trying to establish those values there doesn't work in case the Partner was new,
            // the Row was newly added, and then gets removed (DataRow has DataRowVersion.Detached in
            // this case, and no Original data that can be accessed!)
            FDeletedRowsAttributeType = ARowToDelete.AttributeType;
            FDeletedRowsValue = ARowToDelete.Value;

            ADeletionQuestion =
                String.Format(Catalog.GetString(
                        "Are you sure you want to delete the following Contact Detail record?\r\n\r\n    Type: '{0}'\r\n    Value: '{1}'"),
                    ARowToDelete.AttributeType, ARowToDelete.Value);

            return true;
        }
        /// <summary>
        /// Checks whether Partner Attributes of the same Attribute Type exist in the database.
        /// </summary>
        /// <param name="AImportedPartnerAttribRow"><see cref="PPartnerAttributeRow" /> that holds the imported data.</param>
        /// <param name="AFoundPartnerAttribDR"><see cref="PPartnerAttributeRow" /> that holds the record that was found -
        /// if one was found, otherwise this is null.</param>
        /// <param name="ATransaction">Instantiated DB Transaction.</param>
        /// <returns>False if the row should be imported as found in the import file, otherwise true.</returns>
        public static bool ExistingPartnerAttributes(PPartnerAttributeRow AImportedPartnerAttribRow,
            out PPartnerAttributeRow AFoundPartnerAttribDR, TDBTransaction ATransaction)
        {
            PPartnerAttributeTable ExistingPartnerAttributeDT;

            AFoundPartnerAttribDR = null;

            // Find existing Partner Attribute(s) of the same AttributeType (ignoring sequence!)
            PPartnerAttributeRow TmpPartnerAttributeRow = new PPartnerAttributeTable().NewRowTyped(false);
            TmpPartnerAttributeRow.PartnerKey = AImportedPartnerAttribRow.PartnerKey;
            TmpPartnerAttributeRow.AttributeType = AImportedPartnerAttribRow.AttributeType;

            ExistingPartnerAttributeDT = PartnerAttributeLoadUsingTemplate(TmpPartnerAttributeRow, null, ATransaction);

            if (ExistingPartnerAttributeDT.Count == 0)
            {
                // No existing Partner Attribute(s) of the same AttributeType -->
                // we want to import the row as found in the import file!
                return false;
            }

            // Existing Partner Attribute(s) of the same AttributeType --> Check to see whether we want to import
            // that Row, or whether we want to overwrite an existing Row with some imported data!
            for (int Counter = 0; Counter < ExistingPartnerAttributeDT.Rows.Count; Counter++)
            {
                if (ExistingPartnerAttributeDT[Counter].Value == AImportedPartnerAttribRow.Value)
                {
                    // This *is* the same Partner Attribute!
                    AFoundPartnerAttribDR = ExistingPartnerAttributeDT[Counter];

                    break;
                }
                else if (AImportedPartnerAttribRow.AttributeType == Ict.Petra.Shared.MPartner.Calculations.ATTR_TYPE_PARTNERS_PRIMARY_CONTACT_METHOD)
                {
                    // This *is* the same Partner Attribute!
                    AFoundPartnerAttribDR = ExistingPartnerAttributeDT[Counter];

                    break;
                }
            }

            if (AFoundPartnerAttribDR != null)
            {
                // Same Partner Attribute --> overwrite the Row that is existing in the DB with some imported data!
                return true;
            }

            // No existing Partner Attribute(s) of the same AttributeType with the same Value -->
            // we want to import the row as found in the import file!
            return false;
        }
Beispiel #17
0
        public static bool SavePartner(PartnerEditTDS AMainDS,
                                       List <string> ASubscriptions,
                                       List <string> APartnerTypes,
                                       bool ASendMail,
                                       string ADefaultEmailAddress,
                                       string ADefaultPhoneMobile,
                                       string ADefaultPhoneLandline,
                                       out TVerificationResultCollection AVerificationResult)
        {
            List <string>  Dummy1, Dummy2;
            string         Dummy3, Dummy4, Dummy5;
            PartnerEditTDS SaveDS;

            AVerificationResult = new TVerificationResultCollection();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            try
            {
                TSubmitChangesResult result = uiconnector.SubmitChanges(
                    ref SaveDS,
                    ref ResponseDS,
                    out AVerificationResult);
                return(result == TSubmitChangesResult.scrOK);
            }
            catch (Exception e)
            {
                TLogging.Log(e.ToString());
                AVerificationResult.Add(new TVerificationResult("error", e.Message, TResultSeverity.Resv_Critical));
                return(false);
            }
        }
        private bool RowHasPhoneAttributeType(PPartnerAttributeRow ADetailRow)
        {
            bool ReturnValue = false;

            for (int Counter = 0; Counter < FPhoneAttributesDV.Count; Counter++)
            {
                if ((ADetailRow.AttributeType == ((PPartnerAttributeTypeRow)FPhoneAttributesDV[Counter].Row).AttributeType)
                    && (ADetailRow.AttributeType != "Fax"))
                {
                    ReturnValue = true;
                    break;
                }
            }

            return ReturnValue;
        }
        private void ValidateDataDetailsManual(PPartnerAttributeRow ARow)
        {
            TVerificationResultCollection VerificationResultCollection = FPetraUtilsObject.VerificationResultCollection;

            TSharedPartnerValidation_Partner.ValidateContactDetailsManual(this, ARow, ref VerificationResultCollection,
                FValidationControlsDict, FValueKind);
        }
        /// <summary>
        /// Takes an PPartnerAttribute Row from the DB and modifies it with data from a PPartnerAttribute Row that got
        /// populated from imported data.
        /// </summary>
        /// <param name="AImportedPartnerAttributeDR">PPartnerAttribute Row that got populated from imported data.</param>
        /// <param name="AExistingPartnerAttributeDR">PPartnerAttribute Row from the DB.</param>
        public static void TakeExistingPartnerAttributeRecordAndModifyIt(PPartnerAttributeRow AImportedPartnerAttributeDR,
            PPartnerAttributeRow AExistingPartnerAttributeDR)
        {
            // First step: Store some details of the to-be-imported record in Variables
            var ImportDRValue = AImportedPartnerAttributeDR.Value;  // only needed for Attribute Type 'PARTNERS_PRIMARY_CONTACT_METHOD'
            var ImportDRComment = AImportedPartnerAttributeDR.Comment;
            var ImportDRPrimary = AImportedPartnerAttributeDR.Primary;
            var ImportDRWithinOrganisation = AImportedPartnerAttributeDR.WithinOrganisation;
            var ImportDRSpecialised = AImportedPartnerAttributeDR.Specialised;
            var ImportDRConfidential = AImportedPartnerAttributeDR.Confidential;
            var ImportDRCurrent = AImportedPartnerAttributeDR.Current;
            var ImportDRNoLongerCurrentFrom = AImportedPartnerAttributeDR.NoLongerCurrentFrom;

            // Second step: Copy all data from the record as it exists in the DB over into the to-be-imported record.
            // This is necessary so that the overwriting of some details of the record (see below) creates DataColumns
            // whose 'Modified' data is different than their 'Current' data (otherwise an 'empty' UPDATE command will
            // be issued against the DB!)
            DataUtilities.CopyAllColumnValues(AExistingPartnerAttributeDR, AImportedPartnerAttributeDR);

            // Make sure the Imported DataRows' DataRowState is no longer 'Added' as we don't want to add it to the
            // database, but want to update the existing row in the database!
            // (All the DataColumns hold 'Current' Data after this!)
            AImportedPartnerAttributeDR.AcceptChanges();

            // Third step: Overwrite some details of the record as it exists in the DB with details of the
            // to-be-imported record. (All these DataColumns will hold 'Modified' Data after this!)
            AImportedPartnerAttributeDR.Value = ImportDRValue;  // only needed for Attribute Type 'PARTNERS_PRIMARY_CONTACT_METHOD'
            AImportedPartnerAttributeDR.Comment = ImportDRComment;
            AImportedPartnerAttributeDR.Primary = ImportDRPrimary;
            AImportedPartnerAttributeDR.WithinOrganisation = ImportDRWithinOrganisation;
            AImportedPartnerAttributeDR.Specialised = ImportDRSpecialised;
            AImportedPartnerAttributeDR.Confidential = ImportDRConfidential;
            AImportedPartnerAttributeDR.Current = ImportDRCurrent;
            AImportedPartnerAttributeDR.NoLongerCurrentFrom = ImportDRNoLongerCurrentFrom;

            // Note: The DataRows' DataRowState is now 'Modified', and that causes the DB Access layer to issue an
            // UPDATE statement later. That statement will update data in each of the DB Tables' columns where a
            // DataColumn holds different data in the 'Current' and 'Modified' versions of a DataColum, i.e. where
            // there is a real difference between the to-be-imported data and the data in the record that is already
            // in the DB.
        }
Beispiel #21
0
        /// <summary>
        /// create PPartnerLocation records for the FAMILY partner, and all the PERSON records of this family
        /// </summary>
        public static void GenerateAddressForFamily(XmlNode ACurrentNode, PFamilyRow AFamilyRow, PartnerEditTDS AMainDS)
        {
            PLocationRow locationRow = AMainDS.PLocation.NewRowTyped();

            locationRow.SiteKey     = 0; // DomainManager.GSiteKey;
            locationRow.LocationKey = (AMainDS.PLocation.Count + 1) * -1;
            locationRow.StreetName  = TXMLParser.GetAttribute(ACurrentNode, "Addr2");
            locationRow.PostalCode  = TXMLParser.GetAttribute(ACurrentNode, "PostCode");
            locationRow.City        = TXMLParser.GetAttribute(ACurrentNode, "City");
            locationRow.County      = TXMLParser.GetAttribute(ACurrentNode, "Province");
            locationRow.CountryCode = TXMLParser.GetAttribute(ACurrentNode, "CountryCode");

            AMainDS.PLocation.Rows.Add(locationRow);

            PPartnerLocationRow familyLocationRow = AMainDS.PPartnerLocation.NewRowTyped();

            familyLocationRow.PartnerKey   = AFamilyRow.PartnerKey;
            familyLocationRow.LocationKey  = locationRow.LocationKey;
            familyLocationRow.SiteKey      = locationRow.SiteKey;
            familyLocationRow.LocationType = MPartnerConstants.LOCATIONTYPE_HOME;
            familyLocationRow.SendMail     = true;

            string gender = TXMLParser.GetAttribute(ACurrentNode, "familySituation");
            Random r      = new Random();

            string email = TXMLParser.GetAttribute(ACurrentNode, "FemaleEmail");

            if ((gender == "singleMan") || ((gender == "family") && (r.Next(2) == 0)))
            {
                email = TXMLParser.GetAttribute(ACurrentNode, "MaleEmail");
            }

            if (email.Length > 0)
            {
                PPartnerAttributeRow partnerAttributeRow = AMainDS.PPartnerAttribute.NewRowTyped();
                partnerAttributeRow.PartnerKey    = AFamilyRow.PartnerKey;
                partnerAttributeRow.AttributeType = MPartnerConstants.ATTR_TYPE_EMAIL;
                partnerAttributeRow.Index         = 0;
                partnerAttributeRow.Primary       = true;
                partnerAttributeRow.Value         = email;
                AMainDS.PPartnerAttribute.Rows.Add(partnerAttributeRow);

                partnerAttributeRow               = AMainDS.PPartnerAttribute.NewRowTyped();
                partnerAttributeRow.PartnerKey    = AFamilyRow.PartnerKey;
                partnerAttributeRow.AttributeType = MPartnerConstants.ATTR_TYPE_PARTNERS_PRIMARY_CONTACT_METHOD;
                partnerAttributeRow.Index         = 9999;
                partnerAttributeRow.Primary       = false;
                partnerAttributeRow.Value         = MPartnerConstants.ATTR_TYPE_EMAIL;
                AMainDS.PPartnerAttribute.Rows.Add(partnerAttributeRow);
            }

            AMainDS.PPartnerLocation.Rows.Add(familyLocationRow);

            DataView FamilyView = new DataView(AMainDS.PPerson);

            FamilyView.RowFilter = PPersonTable.GetFamilyKeyDBName() + " = " + AFamilyRow.PartnerKey.ToString();
            FamilyView.Sort      = PPersonTable.GetFamilyIdDBName();

            // for each person, also create a location record
            for (int countPerson = 0; countPerson < FamilyView.Count; countPerson++)
            {
                PPersonRow personRow = (PPersonRow)FamilyView[countPerson].Row;

                PPartnerLocationRow personLocationRow = AMainDS.PPartnerLocation.NewRowTyped();
                personLocationRow.PartnerKey   = personRow.PartnerKey;
                personLocationRow.LocationKey  = familyLocationRow.LocationKey;
                personLocationRow.SiteKey      = familyLocationRow.SiteKey;
                personLocationRow.LocationType = MPartnerConstants.LOCATIONTYPE_HOME;
                personLocationRow.SendMail     = false;
                AMainDS.PPartnerLocation.Rows.Add(personLocationRow);
            }
        }
        private void BeforeShowDetailsManual(PPartnerAttributeRow ARow)
        {
            FRunningInsideShowDetails = true;

            if (ARow != null)
            {
                btnDelete.Enabled = true;

                if (FMainDS.PPartnerAttributeType != null)
                {
                    DataRow[] ParnterAttributeRow = FMainDS.PPartnerAttributeType.Select(
                        PPartnerAttributeTypeTable.GetAttributeTypeDBName() + " = " + "'" + ARow.AttributeType + "'");

                    if (ParnterAttributeRow.Length > 0)
                    {
                        SelectCorrespondingCategory((PPartnerAttributeTypeRow)ParnterAttributeRow[0]);
                    }

//                    cmbContactType.SetSelectedString(ARow.AttributeType, -1);
                }
            }
            else
            {
                cmbContactCategory.SelectedIndex = 0;
            }

            cmbContactCategory.Enabled = (ARow.RowState == DataRowState.Added);
        }