Beispiel #1
0
        public new IContact Get(Guid contactId)
        {
            string[] facets = new string[8]
            {
                "Personal",
                "Addresses",
                "Emails",
                "PhoneNumbers",
                "Classification",
                "EngagementMeasures",
                "SalesforceContact",
                "CustomSalesforceContact"
            };
            Contact                            contact = this.GetContact(contactId, facets);
            PersonalInformation                facet1  = this.TryGetFacet <PersonalInformation>(contact, "Personal");
            AddressList                        facet2  = this.TryGetFacet <AddressList>(contact, "Addresses");
            EmailAddressList                   facet3  = this.TryGetFacet <EmailAddressList>(contact, "Emails");
            PhoneNumberList                    facet4  = this.TryGetFacet <PhoneNumberList>(contact, "PhoneNumbers");
            Classification                     facet5  = this.TryGetFacet <Classification>(contact, "Classification");
            EngagementMeasures                 facet6  = this.TryGetFacet <EngagementMeasures>(contact, "EngagementMeasures");
            SalesforceContactInformation       facet7  = this.TryGetFacet <SalesforceContactInformation>(contact, "SalesforceContact");
            CustomSalesforceContactInformation facet8  = this.TryGetFacet <CustomSalesforceContactInformation>(contact, "CustomSalesforceContact");

            return((IContact)this.CreateContact(contact.Id.GetValueOrDefault(), facet5, facet6, facet1, facet3, facet4, facet2, facet7, facet8, contact.Identifiers.ToList <ContactIdentifier>()));
        }
Beispiel #2
0
        private bool SetPhone(UserProfile profile, XConnect.Contact contact, XConnectClient client)
        {
            var phoneNumber = profile[Accounts.Constants.UserProfile.Fields.PhoneNumber];

            if (string.IsNullOrEmpty(phoneNumber))
            {
                return(false);
            }
            var phoneNumbers = contact.PhoneNumbers();

            if (phoneNumbers == null)
            {
                phoneNumbers = new PhoneNumberList(new PhoneNumber(null, phoneNumber), null);
            }
            else
            {
                if (phoneNumbers.PreferredPhoneNumber?.Number == phoneNumber)
                {
                    return(false);
                }
                phoneNumbers.PreferredPhoneNumber = new PhoneNumber(null, phoneNumber);
            }
            client.SetFacet(contact, PhoneNumberList.DefaultFacetKey, phoneNumbers);
            return(true);
        }
        public void Constructor()
        {
            PhoneNumberList phoneNumbers;

            phoneNumbers = new PhoneNumberList();
            Assert.IsNotNull(phoneNumbers);
        }
Beispiel #4
0
        public bool SetFacets(UserProfile profile, Contact contact, IXdbContext client)
        {
            var phoneNumber = profile[Accounts.Constants.UserProfile.Fields.PhoneNumber];

            if (string.IsNullOrEmpty(phoneNumber))
            {
                return(false);
            }
            var phoneNumbers = contact.GetFacet <PhoneNumberList>(PhoneNumberList.DefaultFacetKey);

            if (phoneNumbers == null)
            {
                phoneNumbers = new PhoneNumberList(new PhoneNumber(null, phoneNumber), null);
            }
            else
            {
                if (phoneNumbers.PreferredPhoneNumber?.Number == phoneNumber)
                {
                    return(false);
                }
                phoneNumbers.PreferredPhoneNumber = new PhoneNumber(null, phoneNumber);
            }
            client.SetFacet(contact, PhoneNumberList.DefaultFacetKey, phoneNumbers);
            return(true);
        }
Beispiel #5
0
        public void TestDoubleOutboundMapping()
        {
            String mapping = "<agent id=\"Repro\" sifVersion=\"2.0\">"
                             + "    <mappings id=\"Default\">"
                             + "        <object object=\"StudentPersonal\">"
                             + "           <field name='PHONE_TYPE'>PhoneNumberList/PhoneNumber/@Type</field>"
                             + "           <field name='PHONE'>PhoneNumberList/PhoneNumber[1]/Number</field>"
                             + "        </object>" + "    </mappings>" + "</agent>";

            IDictionary map = new Dictionary <String, String>();

            map.Add("PHONE_TYPE", "1234");
            map.Add("PHONE", "715-555-5555");
            StringMapAdaptor sma = new StringMapAdaptor(map);
            StudentPersonal  sp  = mapToStudentPersonal(sma, mapping, null);

            Assertion.AssertNotNull("Student should not be null", sp);
            PhoneNumberList phoneList = sp.PhoneNumberList;

            Assertion.AssertEquals("One Phone", 1, phoneList.ChildCount);

            PhoneNumber phone = (PhoneNumber)phoneList.GetChildList()[0];

            Assertion.AssertNotNull("Phone should not be null", phone);
            Assertion.AssertEquals("Phone type", "1234", phone.Type);
            Assertion.AssertEquals("PhoneNumber", "715-555-5555", phone.Number);
        }
Beispiel #6
0
 /// <summary>
 /// Create a Person instance.
 /// </summary>
 /// <param name="userContext">User context.</param>
 public Person(IUserContext userContext)
 {
     // Set default values.
     Addresses            = new AddressList();
     AdministrationRoleId = null;
     BirthYear            = null;
     DataContext          = new DataContext(userContext);
     DeathYear            = null;
     FirstName            = null;
     Gender = CoreData.UserManager.GetPersonGender(userContext,
                                                   PersonGenderId.Unspecified);
     GUID                    = Settings.Default.PersonGUIDTemplate;
     Id                      = Int32.MinValue;
     Locale                  = userContext.Locale;
     MiddleName              = null;
     PhoneNumbers            = new PhoneNumberList();
     Presentation            = null;
     ShowEmailAddress        = false;
     ShowPersonalInformation = false;
     ShowPresentation        = false;
     TaxonNameTypeId         = (Int32)(TaxonNameCategoryId.ScientificName);
     UpdateInformation       = new UpdateInformation();
     URL                     = null;
     _user                   = null;
     _userId                 = null;
 }
Beispiel #7
0
        private bool SetPhone(ContactFacetData data, XConnect.Contact contact, XConnectClient client)
        {
            var phoneNumber = data.PhoneNumber;

            if (string.IsNullOrEmpty(phoneNumber))
            {
                return(false);
            }
            var phoneNumbers = contact.PhoneNumbers();

            if (phoneNumbers == null)
            {
                phoneNumbers = new PhoneNumberList(new PhoneNumber(null, phoneNumber), null);
            }
            else
            {
                if (phoneNumbers.PreferredPhoneNumber?.Number == phoneNumber)
                {
                    return(false);
                }
                phoneNumbers.PreferredPhoneNumber = new PhoneNumber(null, phoneNumber);
            }
            client.SetFacet(contact, PhoneNumberList.DefaultFacetKey, phoneNumbers);
            return(true);
        }
 private PhoneNumberList GetPhoneNumbers(Boolean refresh)
 {
     if (_phoneNumbers.IsNull() || refresh)
     {
         _phoneNumbers = new PhoneNumberList();
         _phoneNumbers.Add(PhoneNumberTest.GetOnePhoneNumber(GetUserContext()));
     }
     return(_phoneNumbers);
 }
Beispiel #9
0
        private void assertStudentPersonal(StudentPersonal sp)
        {
            DateTime birthDate = new DateTime(1990, 1, 1);

            Assertion.AssertEquals("First Name", "Betty", sp.Name.FirstName);
            Assertion.AssertEquals("Middle Name", "George", sp.Name.MiddleName);
            Assertion.AssertEquals("Last Name", "Johnson", sp.Name.LastName);
            Assertion.AssertEquals("Student Number", "998", sp.OtherIdList.ItemAt(0).TextValue);
            Assertion.AssertEquals("Birthdate", birthDate, sp.Demographics.BirthDate.Value);
            Assertion.AssertEquals("Ethnicity", "H", sp.Demographics.RaceList.ItemAt(0).Code);

            PhoneNumberList pnl = sp.PhoneNumberList;

            Assertion.AssertNotNull("PhoneNumberList", pnl);

            PhoneNumber homePhone = pnl[PhoneNumberType.SIF1x_HOME_PHONE];

            Assertion.AssertNotNull("Home Phone is null", homePhone);
            Assertion.AssertEquals("Home Phone", "202-358-6687", homePhone
                                   .Number);

            PhoneNumber cellPhone = pnl
                                    [PhoneNumberType.SIF1x_PERSONAL_CELL];

            Assertion.AssertNotNull("cellPhone Phone is null", cellPhone);
            Assertion.AssertEquals("Cell Phone", "202-502-4856", cellPhone.Number);

            SifXPathContext xpathContext = SifXPathContext.NewSIFContext(sp, SifVersion.SIF20r1);

            assertByXPath(xpathContext, "AddressList/Address/Street/Line1",
                          "321 Oak St");
            assertByXPath(xpathContext, "AddressList/Address/Street/Line1",
                          "321 Oak St");
            assertByXPath(xpathContext, "AddressList/Address/Street/Line2",
                          "APT 11");
            assertByXPath(xpathContext, "AddressList/Address/City", "Metropolis");
            assertByXPath(xpathContext, "AddressList/Address/StateProvince", "IL");
            assertByXPath(xpathContext, "AddressList/Address/Country", "US");
            assertByXPath(xpathContext, "AddressList/Address/PostalCode", "321546");

            /*
             * These assertions are currently commented out because the Adk does not
             * currently support Repeatable elements that have wildcard attributes
             *
             * PhoneNumber number = sp.PhoneNumber( PhoneNumberType.PHONE );
             * Assertion.AssertNotNull( "Alternate Phone Element is null", number );
             * Assertion.AssertEquals( "Alternate Phone", "201-668-1245",
             * number.ToString() );
             */

            Assertion.AssertEquals("OriginalGradYear", 2005, sp.OnTimeGraduationYear.Value);
            Assertion.AssertEquals("Projected", 2007, sp.ProjectedGraduationYear.Value);
            Assertion.AssertNotNull("Actual Grad Year", sp.GraduationDate.Value);
            Assertion.AssertEquals("OriginalGradYear", 2007, sp.GraduationDate.Year);
        }
Beispiel #10
0
        private bool SetPhone(ContactFacetData data, XConnect.Contact contact, XConnectClient client)
        {
            var phoneNumber = data.PhoneNumber;

            if (string.IsNullOrEmpty(phoneNumber))
            {
                return(false);
            }
            var phoneNumberFacet = new PhoneNumberList(new PhoneNumber(String.Empty, phoneNumber), "Work Phone");

            client.SetFacet(contact, PhoneNumberList.DefaultFacetKey, phoneNumberFacet);
            return(true);
        }
Beispiel #11
0
        /// <summary>
        /// String representation of <see cref="AddressBookContact"/>.
        /// </summary>
        public override string ToString()
        {
            System.Text.StringBuilder _builder = new System.Text.StringBuilder();

            // Append first name, last name and icon
            _builder.AppendFormat("[AddressBookContact: FirstName={0}, LastName={1}, ImagePath={2}, ", FirstName, LastName, ImagePath);

            // Append mobile numbers
            _builder.AppendFormat("PhoneNumberList={0}", PhoneNumberList.ToJSON());

            // Append email id's
            _builder.AppendFormat("EmailIdList={0}]", EmailIDList.ToJSON());

            return(_builder.ToString());
        }
        public void SquareBracketOperator()
        {
            PhoneNumberList newPhoneNumberList, oldPhoneNumberList;
            Int32           phoneNumberIndex;

            oldPhoneNumberList = GetPhoneNumbers(true);
            newPhoneNumberList = new PhoneNumberList();
            for (phoneNumberIndex = 0; phoneNumberIndex < oldPhoneNumberList.Count; phoneNumberIndex++)
            {
                newPhoneNumberList.Add(oldPhoneNumberList[oldPhoneNumberList.Count - phoneNumberIndex - 1]);
            }
            for (phoneNumberIndex = 0; phoneNumberIndex < oldPhoneNumberList.Count; phoneNumberIndex++)
            {
                Assert.AreEqual(newPhoneNumberList[phoneNumberIndex], oldPhoneNumberList[oldPhoneNumberList.Count - phoneNumberIndex - 1]);
            }
        }
        public void CheckParameters()
        {
            if (!PhoneNumberList.Any())
            {
                throw new InvalidArgumentException("收件人为空", JdCloudSmsConstants.ServiceName, 401);
            }

            if (PhoneNumberList.Count > 100)
            {
                throw new InvalidArgumentException("收件人不能超过 100 个", JdCloudSmsConstants.ServiceName, 402);
            }

            if (!Params.Any())
            {
                throw new InvalidArgumentException("内容不能为空", JdCloudSmsConstants.ServiceName, 401);
            }
        }
Beispiel #14
0
        public void CheckParameters()
        {
            if (!PhoneNumberList.Any())
            {
                throw new InvalidArgumentException("收件人为空", HuaweiCloudSmsConstants.ServiceName, 401);
            }

            if (PhoneNumberList.Count > 1000)
            {
                throw new InvalidArgumentException("收件人不能超过 1000 个", HuaweiCloudSmsConstants.ServiceName, 402);
            }

            if (PhoneNumberList.Any(p => !p.IsValid()))
            {
                throw new InvalidArgumentException("收件人号码长度不能超过 21 位", HuaweiCloudSmsConstants.ServiceName, 403);
            }
        }
Beispiel #15
0
        private static void UpdatePhoneNumberFacet(XConnectClient client, Contact contact)
        {
            var facet = contact.GetFacet <PhoneNumberList>(PhoneNumberList.DefaultFacetKey);

            if (facet?.PreferredPhoneNumber != null)
            {
                facet.PreferredPhoneNumber.CountryCode = _fakeContact.PhoneCountryCode;
                facet.PreferredPhoneNumber.Number      = _fakeContact.PhoneNumber;
                facet.PreferredPhoneNumber.AreaCode    = _fakeContact.PhoneAreaCode;
                client.SetFacet(contact, PhoneNumberList.DefaultFacetKey, facet);
            }
            else
            {
                PhoneNumberList phoneNumbers = new PhoneNumberList(new PhoneNumber(_fakeContact.PhoneCountryCode, _fakeContact.PhoneNumber), "Home");
                client.SetFacet(contact, PhoneNumberList.DefaultFacetKey, phoneNumbers);
            }
        }
 /// <summary>
 /// Create an Organization instance.
 /// </summary>
 /// <param name="userContext">User context.</param>
 public Organization(IUserContext userContext)
 {
     // Set default values.
     Addresses            = new AddressList();
     AdministrationRoleId = null;
     DataContext          = new DataContext(userContext);
     Description          = null;
     HasSpeciesCollection = false;
     GUID              = Settings.Default.OrganizationGUIDTemplate;
     Id                = Int32.MinValue;
     Name              = null;
     Category          = new OrganizationCategory(Int32.MinValue, @"OrganizationCategoryName", null, Int32.MinValue, Int32.MinValue, new UpdateInformation(), DataContext);
     PhoneNumbers      = new PhoneNumberList();
     ShortName         = null;
     UpdateInformation = new UpdateInformation();
     ValidFromDate     = DateTime.Now;
     ValidToDate       = ValidFromDate + new TimeSpan(Settings.Default.ValidToDateYearIncrement * 365, 0, 0, 0);
 }
        public void testLEAInfoPhones()
        {
            String customMappings = "<agent id='Repro' sifVersion='2.0'>"
                                    + "   <mappings id='Default'>"
                                    + "     <object object='LEAInfo'>"
                                    +
                                    "		<field name='DISTRICT_PHONE' sifVersion='-1.5r1'>PhoneNumber[@Format='NA',@Type='TE']</field>"
                                    +
                                    "		<field name='CONTACT_PHONE' sifVersion='-1.5r1'>LEAContact/ContactInfo/PhoneNumber[@Format='NA',@Type='TE']</field>"
                                    + "</object></mappings></agent>";

            Adk.SifVersion = SifVersion.SIF15r1;

            IDictionary map = new Hashtable();

            map.Add("DISTRICT_PHONE", "912-555-6658");
            map.Add("CONTACT_PHONE", "912-888-6658");
            StringMapAdaptor sma = new StringMapAdaptor(map);
            LEAInfo          obj = new LEAInfo();

            doOutboundMapping(sma, obj, customMappings, null);

            PhoneNumberList pnl = obj.PhoneNumberList;

            Assertion.AssertNotNull("LeaInfo/PhoneNumberList is Null", pnl);
            PhoneNumber phone = obj.PhoneNumberList.ItemAt(0);

            Assertion.AssertEquals("Format", "NA", phone.Format);
            Assertion.AssertEquals("Type", "TE", phone.Type);
            Assertion.AssertEquals("Number", "912-555-6658", phone.Number);

            LEAContact contact = obj.LEAContactList.ItemAt(0);

            phone = contact.ContactInfo.PhoneNumberList.ItemAt(0);
            Assertion.AssertEquals("Contact Format", "NA", phone.Format);
            Assertion.AssertEquals("Contact Type", "TE", phone.Type);
            Assertion.AssertEquals("Contact Number", "912-888-6658", phone.Number);
        }
Beispiel #18
0
        protected override void CopyDataToModel(hcc_User data, CustomerAccount model)
        {
            model.Bvin             = data.bvin;
            model.StoreId          = data.StoreId;
            model.LastUpdatedUtc   = data.LastUpdated;
            model.CreationDateUtc  = data.CreationDate;
            model.Email            = data.Email;
            model.FailedLoginCount = data.FailedLoginCount;
            model.FirstName        = data.FirstName;
            model.LastLoginDateUtc = data.LastLoginDate;
            model.LastName         = data.LastName;
            model.Locked           = data.Locked == 1;
            model.LockedUntilUtc   = data.LockedUntil;
            model.Notes            = data.Comment;
            model.Password         = data.Password;
            model.PricingGroupId   = data.PricingGroup;
            model.TaxExempt        = data.TaxExempt == 1;

            Address shipAddr = null;
            Address billAddr = null;

            try
            {
                shipAddr        = Json.ObjectFromJson <Address>(data.ShippingAddress);
                billAddr        = Json.ObjectFromJson <Address>(data.BillingAddress);
                model.Addresses = AddressList.FromJson(data.AddressBook);
                model.Phones    = PhoneNumberList.FromJson(data.Phones);
            }
            catch (Exception ex)
            {
                EventLog.LogEvent(ex);
            }
            model.ShippingAddress = shipAddr ?? new Address();

            model.BillingAddress = billAddr ?? new Address();
        }
Beispiel #19
0
        public void UpdateSession(Session session, RequestInfo requestInfo)
        {
            #region Local Declarations

            var  firstNameValue   = string.Empty;
            var  lastNameValue    = string.Empty;
            var  emailValue       = string.Empty;
            var  genderValue      = string.Empty;
            var  phoneNumberValue = string.Empty;
            var  birthDateValue   = DateTime.MinValue;
            var  jobTitleValue    = string.Empty;
            var  phoneNumber      = string.Empty;
            var  avatar           = string.Empty;
            var  addressValue     = string.Empty;
            Item itemValue        = null;

            #endregion

            #region Get Personal Contact Information

            //First Name
            requestInfo.SetIfVariablePresent("ContactFirstName", firstName =>
            {
                firstNameValue = firstName;
            });
            //Last Name
            requestInfo.SetIfVariablePresent("ContactLastName", lastName =>
            {
                lastNameValue = lastName;
            });
            //Gender
            requestInfo.SetIfVariablePresent("ContactGender", gender =>
            {
                genderValue = gender;
            });
            //Birth Date
            requestInfo.SetIfVariablePresent("ContactBirthDate", date =>
            {
                if (string.IsNullOrEmpty(date))
                {
                    return;
                }

                birthDateValue = DateTime.ParseExact(date.Substring(0, 8), "yyyyMMdd", null);
            });
            //Job Title
            requestInfo.SetIfVariablePresent("ContactJobTitle", jobTitle =>
            {
                jobTitleValue = jobTitle;
            });

            #endregion

            #region Get Address Information

            //Address
            requestInfo.SetIfVariablePresent("ContactAddress", address =>
            {
                addressValue = address;
            });

            #endregion

            #region Get PhoneNumber

            //Phone Number
            requestInfo.SetIfVariablePresent("ContactPhone", phone =>
            {
                phoneNumberValue = phone;
            });

            #endregion

            #region Get Avatar Information

            //Picture
            requestInfo.SetIfVariablePresent("ContactPicture", pictureItemID =>
            {
                if (string.IsNullOrEmpty(pictureItemID))
                {
                    return;
                }

                var item = (Context.ContentDatabase ?? Context.Database).GetItem(pictureItemID);

                if (item == null)
                {
                    return;
                }

                itemValue = item;
            });

            #endregion

            #region Get Email Information

            requestInfo.SetIfVariablePresent("ContactEmail", email =>
            {
                emailValue = email;
            });

            #endregion

            var xGenIdentifier = Tracker.Current.Contact.Identifiers.FirstOrDefault(x => x.Source == "xGenerator");

            //Use the email to uniquely identify the contact between visits.
            if (xGenIdentifier == null)
            {
                if (!String.IsNullOrWhiteSpace(emailValue))
                {
                    Tracker.Current.Session.IdentifyAs("xGenerator", emailValue);
                }
                else
                {
                    Tracker.Current.Session.IdentifyAs("xGenerator", Tracker.Current.Contact.ContactId.ToString("N"));
                }
            }

            var manager = Sitecore.Configuration.Factory.CreateObject("tracking/contactManager", true) as Sitecore.Analytics.Tracking.ContactManager;

            if (Tracker.Current.Contact.IsNew)
            {
                Log.Info($"ExperienceGenerator ContactDataProcessor: Tracker.Current.Contact.IsNew: {Tracker.Current.Contact.IsNew}, TrackerContactId: {Tracker.Current.Contact.ContactId:N}", this);

                if (manager != null)
                {
                    // Save contact to xConnect; at this point, a contact has an anonymous
                    // TRACKER IDENTIFIER, which follows a specific format. Do not use the contactId overload
                    // and make sure you set the ContactSaveMode as demonstrated
                    Sitecore.Analytics.Tracker.Current.Contact.ContactSaveMode = ContactSaveMode.AlwaysSave;
                    manager.SaveContactToCollectionDb(Sitecore.Analytics.Tracker.Current.Contact);

                    Log.Info($"ExperienceGenerator ContactDataProcessor: Session Identified using xGenerator", this);

                    // Now that the contact is saved, you can retrieve it using the tracker identifier

                    IdentifiedContactReference trackerIdentifier;
                    var anyIdentifier = Tracker.Current.Contact.Identifiers.FirstOrDefault(x => (x.Source == "xGenerator" || x.Source == Sitecore.Analytics.XConnect.DataAccess.Constants.IdentifierSource));
                    if (anyIdentifier != null)
                    {
                        trackerIdentifier = new IdentifiedContactReference(anyIdentifier.Source, anyIdentifier.Identifier);;
                    }
                    else
                    {
                        trackerIdentifier = new IdentifiedContactReference(Sitecore.Analytics.XConnect.DataAccess.Constants.IdentifierSource, Tracker.Current.Contact.ContactId.ToString("N"));
                    }

                    using (var client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
                    {
                        try
                        {
                            var contact = client.Get <Contact>(trackerIdentifier, new ContactExecutionOptions());

                            if (contact != null)
                            {
                                Log.Info($"ExperienceGenerator ContactDataProcessor: FirstName: {firstNameValue}, LastName: {lastNameValue}, Email: {emailValue}", this);

                                client.SetFacet <PersonalInformation>(contact, PersonalInformation.DefaultFacetKey, new PersonalInformation()
                                {
                                    FirstName = firstNameValue ?? string.Empty,
                                    LastName  = lastNameValue ?? string.Empty,
                                    Birthdate = birthDateValue,
                                    JobTitle  = jobTitleValue ?? string.Empty,
                                    Gender    = genderValue ?? string.Empty
                                });

                                Log.Info($"ExperienceGenerator ContactDataProcessor: PersonalInformationFacet set for New Contact", this);

                                if (!string.IsNullOrWhiteSpace(emailValue))
                                {
                                    var emails = new EmailAddressList(new EmailAddress(emailValue, true), "Home");
                                    client.SetFacet(contact, EmailAddressList.DefaultFacetKey, emails);
                                    Log.Info($"ExperienceGenerator ContactDataProcessor: EmailFacet set for New Contact", this);
                                }

                                if (!string.IsNullOrWhiteSpace(addressValue))
                                {
                                    var addresses = new AddressList(new Address {
                                        AddressLine1 = addressValue
                                    }, "Home");
                                    client.SetFacet(contact, AddressList.DefaultFacetKey, addresses);
                                    Log.Info($"ExperienceGenerator ContactDataProcessor: AddressFacet set for New Contact", this);
                                }

                                if (!string.IsNullOrWhiteSpace(phoneNumberValue))
                                {
                                    var phoneNumbers = new PhoneNumberList(new PhoneNumber(String.Empty, phoneNumberValue), "Home");
                                    client.SetFacet(contact, PhoneNumberList.DefaultFacetKey, phoneNumbers);
                                    Log.Info($"ExperienceGenerator ContactDataProcessor: PhoneNumberFacet set for New Contact", this);
                                }

                                client.Submit();
                            }
                        }
                        catch (XdbExecutionException ex)
                        {
                            Log.Error($"ExperienceGenerator ContactDataProcessor: There was an exception while trying to set facet information for new contact, ContactId: {Tracker.Current.Contact.ContactId:N}", ex, this);
                        }
                    }
                }
            }
            else if (!Tracker.Current.Contact.IsNew && manager != null)
            {
                Log.Info($"ExperienceGenerator ContactDataProcessor: Tracker.Current.Contact.IsNew: {Tracker.Current.Contact.IsNew}, TrackerContactId: {Tracker.Current.Contact.ContactId:N}", this);
                var anyIdentifier = Tracker.Current.Contact.Identifiers.FirstOrDefault(x => x.Source == "xGenerator");

                if (anyIdentifier != null)
                {
                    Log.Info($"ExperienceGenerator ContactDataProcessor: FirstName: {firstNameValue}, LastName: {lastNameValue}, Email: {emailValue}", this);
                    Log.Info($"ExperienceGenerator ContactDataProcessor: TrackerContactId: {Tracker.Current.Contact.ContactId:N}, Tracker.Current.Contact.IsNew: False, Tracker.Current.Contact.Facets: {Tracker.Current.Contact.Facets.Count}", this);
                    using (var client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
                    {
                        try
                        {
                            var contact = client.Get <Contact>(
                                new IdentifiedContactReference(anyIdentifier.Source, anyIdentifier.Identifier),
                                new ContactExecutionOptions(
                                    new ContactExpandOptions(PersonalInformation.DefaultFacetKey,
                                                             EmailAddressList.DefaultFacetKey,
                                                             PhoneNumberList.DefaultFacetKey,
                                                             AddressList.DefaultFacetKey)));

                            if (contact != null)
                            {
                                Log.Info($"ExperienceGenerator ContactDataProcessor: TrackerContactId: {Tracker.Current.Contact.ContactId:N}, XConnectContactId: {contact.Id.ToString()}, Contact using anyIdentifier loaded with requested ContactExpandOptions", this);

                                var personalInformationFacet = contact.GetFacet <PersonalInformation>(PersonalInformation.DefaultFacetKey);
                                var emailFacet        = contact.GetFacet <EmailAddressList>(EmailAddressList.DefaultFacetKey);
                                var phoneNumbersFacet = contact.GetFacet <PhoneNumberList>(PhoneNumberList.DefaultFacetKey);
                                var addressFacet      = contact.GetFacet <AddressList>(AddressList.DefaultFacetKey);

                                if (personalInformationFacet != null)
                                {
                                    Log.Info($"ExperienceGenerator ContactDataProcessor: TrackerContactId: {Tracker.Current.Contact.ContactId:N}, XConnectContactId: {contact.Id.ToString()}, PersonalInformationFacet is not null", this);
                                    personalInformationFacet.FirstName = firstNameValue ?? string.Empty;
                                    personalInformationFacet.LastName  = lastNameValue ?? string.Empty;
                                    personalInformationFacet.Birthdate = birthDateValue;
                                    personalInformationFacet.JobTitle  = jobTitleValue ?? string.Empty;
                                    personalInformationFacet.Gender    = genderValue ?? string.Empty;

                                    client.SetFacet(contact, PersonalInformation.DefaultFacetKey, personalInformationFacet);
                                }
                                else
                                {
                                    Log.Info($"ExperienceGenerator ContactDataProcessor: TrackerContactId: {Tracker.Current.Contact.ContactId:N}, XConnectContactId: {contact.Id.ToString()}, PersonalInformationFacet is null", this);
                                    client.SetFacet <PersonalInformation>(contact, PersonalInformation.DefaultFacetKey, new PersonalInformation()
                                    {
                                        FirstName = firstNameValue ?? string.Empty,
                                        LastName  = lastNameValue ?? string.Empty,
                                        Birthdate = birthDateValue,
                                        JobTitle  = jobTitleValue ?? string.Empty,
                                        Gender    = genderValue ?? string.Empty
                                    });
                                }

                                if (!string.IsNullOrWhiteSpace(emailValue))
                                {
                                    if (emailFacet != null)
                                    {
                                        if (string.IsNullOrEmpty(emailFacet.PreferredEmail.SmtpAddress))
                                        {
                                            Log.Info($"ExperienceGenerator ContactDataProcessor: TrackerContactId: {Tracker.Current.Contact.ContactId:N}, XConnectContactId: {contact.Id.ToString()}, EmailFacet is not null", this);
                                            emailFacet.PreferredEmail = new EmailAddress(emailValue, true);
                                            emailFacet.PreferredKey   = "Home";
                                            client.SetFacet(contact, EmailAddressList.DefaultFacetKey, emailFacet);
                                        }
                                    }
                                    else
                                    {
                                        Log.Info($"ExperienceGenerator ContactDataProcessor: TrackerContactId: {Tracker.Current.Contact.ContactId:N}, XConnectContactId: {contact.Id.ToString()}, EmailFacet is null", this);
                                        var emails = new EmailAddressList(new EmailAddress(emailValue, true), "Home");
                                        client.SetFacet(contact, EmailAddressList.DefaultFacetKey, emails);
                                    }
                                }

                                if (!string.IsNullOrWhiteSpace(addressValue))
                                {
                                    if (addressFacet != null)
                                    {
                                        if (string.IsNullOrEmpty(addressFacet.PreferredAddress.AddressLine1))
                                        {
                                            Log.Info($"ExperienceGenerator ContactDataProcessor: TrackerContactId: {Tracker.Current.Contact.ContactId:N}, XConnectContactId: {contact.Id.ToString()}, AddressFacet is not null", this);
                                            addressFacet.PreferredAddress = new Address()
                                            {
                                                AddressLine1 = addressValue
                                            };
                                            addressFacet.PreferredKey = "Home";
                                            client.SetFacet(contact, AddressList.DefaultFacetKey, addressFacet);
                                        }
                                    }
                                    else
                                    {
                                        Log.Info($"ExperienceGenerator ContactDataProcessor: TrackerContactId: {Tracker.Current.Contact.ContactId:N}, XConnectContactId: {contact.Id.ToString()}, AddressFacet is null", this);
                                        var addresses = new AddressList(new Address {
                                            AddressLine1 = addressValue
                                        }, "Home");
                                        client.SetFacet(contact, AddressList.DefaultFacetKey, addresses);
                                    }
                                }

                                if (!string.IsNullOrWhiteSpace(phoneNumberValue))
                                {
                                    if (phoneNumbersFacet != null)
                                    {
                                        if (string.IsNullOrEmpty(phoneNumbersFacet.PreferredPhoneNumber.Number))
                                        {
                                            Log.Info($"ExperienceGenerator ContactDataProcessor: TrackerContactId: {Tracker.Current.Contact.ContactId:N}, XConnectContactId: {contact.Id.ToString()}, PhoneNumbersFacet is not null", this);
                                            phoneNumbersFacet.PreferredPhoneNumber = new PhoneNumber(String.Empty, phoneNumberValue);
                                            phoneNumbersFacet.PreferredKey         = "Home";
                                            client.SetFacet(contact, PhoneNumberList.DefaultFacetKey, phoneNumbersFacet);
                                        }
                                    }
                                    else
                                    {
                                        Log.Info($"ExperienceGenerator ContactDataProcessor: TrackerContactId: {Tracker.Current.Contact.ContactId:N}, XConnectContactId: {contact.Id.ToString()}, PhoneNumbersFacet is null", this);
                                        var phoneNumbers = new PhoneNumberList(new PhoneNumber(String.Empty, phoneNumberValue), "Home");
                                        client.SetFacet(contact, PhoneNumberList.DefaultFacetKey, phoneNumbers);
                                    }
                                }

                                client.Submit();
                            }
                        }
                        catch (XdbExecutionException ex)
                        {
                            Log.Error($"ExperienceGenerator ContactDataProcessor: There was an exception while trying to set facet information for known contact, ContactId: {Tracker.Current.Contact.ContactId:N}", ex, this);
                        }
                    }
                }
            }
        }
Beispiel #20
0
        public static StudentPersonal CreateStudentPersonal()
        {
            StudentPersonal sp = new StudentPersonal();

            AlertMessages alm = new AlertMessages();

            alm.AddAlertMessage(AlertMessageType.LEGAL, "This is the Legal Alert for Joe Student");
            sp.AlertMessages = alm;

            // TODO: Consider adding helper methods to the ADK that allow
            // list elements to be set or gotten from the parent?
            OtherIdList oidList = new OtherIdList();

            oidList.AddOtherId(OtherIdType.SIF1x_OTHER, "P00001");
            oidList.AddOtherId(OtherIdType.SIF1x_HEATH_RECORD, "WB0025");
            oidList.AddOtherId(OtherIdType.SIF1x_SSN, "123-45-6789");

            sp.OtherIdList = oidList;

            Name name = new Name(NameType.BIRTH, "Student", "Joe");

            name.MiddleName    = "";
            name.PreferredName = "Joe";
            sp.Name            = name;

            EmailList elist = new EmailList();

            elist.AddEmail(EmailType.PRIMARY, "*****@*****.**");
            sp.EmailList = elist;

            sp.OnTimeGraduationYear = 1982;
            Demographics demo = new Demographics();

            demo.BirthDate = new DateTime(1981, 12, 20);
            demo.SetCitizenshipStatus(CitizenshipStatus.USCITIZEN);

            CountriesOfCitizenship countries = new CountriesOfCitizenship();

            countries.AddCountryOfCitizenship(CountryCode.US);
            countries.AddCountryOfCitizenship(CountryCode.Wrap("CA"));
            demo.CountriesOfCitizenship = countries;
            demo.SetCountryOfBirth(CountryCode.US);

            CountriesOfResidency cre = new CountriesOfResidency(new Country(CountryCode.IE));

            demo.CountriesOfResidency = cre;

            demo.SetStateOfBirth(StatePrCode.AK);
            sp.Demographics = demo;
            Address addr = new Address();

            addr.City = "Salt Lake City";
            addr.SetStateProvince(StatePrCode.UT);
            addr.SetCountry(CountryCode.US);
            addr.PostalCode = "84102";
            Street str = new Street();

            str.Line1           = "1 IBM Plaza";
            str.ApartmentNumber = "2000";
            str.Line2           = "Suite 2000";
            str.Line3           = "Salt Lake City, UT 84102";
            str.StreetName      = "IBM";
            str.StreetNumber    = "1";
            str.StreetType      = "Plaza";
            str.ApartmentType   = "Suite";
            addr.Street         = str;
            sp.AddAddressList(PickupOrDropoff.NA, "MoTuWeThFrSaSu", addr);

            PhoneNumberList plist = new PhoneNumberList();

            plist.AddPhoneNumber(PhoneNumberType.SIF1x_HOME_PHONE, "(312) 555-1234");
            sp.PhoneNumberList = plist;

            //  Test changing the name
            sp.SetName(NameType.BIRTH, "STUDENT", "JOE");

            return(sp);
        }
 public PhoneNumberListTest()
 {
     _phoneNumbers = null;
 }
Beispiel #22
0
        public bool SetOnlineContactDetails(string Source, ContactViewModel model)
        {
            XConnectClientService _xc = new XConnectClientService();

            // Get or Create a new contact
            Contact contact = _xc.GetOrSetContact(Source);

            PersonalInformation pi = new PersonalInformation
            {
                Title             = model.Prefix,
                FirstName         = model.FirstName,
                LastName          = model.LastName,
                JobTitle          = model.JobTitle,
                Birthdate         = model.Birthday,
                PreferredLanguage = model.PreferredLanguage,
                Gender            = model.Gender
            };

            _xc.SetPersonalInformationFacet(Source, pi);


            if (model.Email != null && !model.Email.Equals(""))
            {
                // create a preferred email address since this is just one
                EmailAddress pe = new EmailAddress(model.Email, true);

                // add email to an email facet (List)
                EmailAddressList el = new EmailAddressList(pe, model.EmailType);

                _xc.SetEmailListFacet(Source, el);
            }

            if (model.PhoneNumber != null && !model.PhoneNumber.Equals(""))
            {
                PhoneNumber ph = new PhoneNumber(model.CountryCode, model.PhoneNumber);

                PhoneNumberList pl = new PhoneNumberList(ph, model.PhoneNumberType);

                _xc.SetPhoneListFacet(Source, pl);
            }


            if (model.AddressLine1 != null)
            {
                Address a = new Address
                {
                    AddressLine1    = model.AddressLine1,
                    AddressLine2    = model.AddressLine2,
                    City            = model.City,
                    StateOrProvince = model.State,
                    CountryCode     = model.CountryCode,
                    PostalCode      = model.PostalCode
                };

                AddressList al = new AddressList(a, model.EmailType);  // Using emailType =='Work' since don't have a address type in model.

                _xc.SetAddressListFacet(Source, al);
            }


            _xc.SetGoal(Source, XConnectSettings.OnlineGoalId, XConnectSettings.OnlineChannelId, "CanvasDesignStudio (Windows NT 10.0; Win64; x64)");



            return(true);
        }
        private static async Task UpdateContactFacet(XConnectClientConfiguration xConfig, string contactId, string firstName, string lastName, string email, string countryCode, string mobileNumber, string customerStatus)
        {
            // Initialize a client using the validated configuration
            using (var client = new XConnectClient(xConfig))
            {
                try
                {
                    Contact contact;
                    //IdentifiedContactReference reference;
                    //ContactReference reference;
                    if (!string.IsNullOrEmpty(contactId))
                    {
                        var reference = new Sitecore.XConnect.ContactReference(Guid.Parse(contactId));
                        contact = client.Get <Contact>(reference, new ContactExpandOptions(new string[] {
                            PersonalInformation.DefaultFacetKey,
                            EmailAddressList.DefaultFacetKey,
                            PhoneNumberList.DefaultFacetKey,
                            CustomerFacets.DefaultFacetKey
                        }));
                    }
                    else
                    {
                        IdentifiedContactReference reference = new IdentifiedContactReference("CustomerRef", email);
                        contact = client.Get <Contact>(reference, new ContactExpandOptions(new string[] {
                            PersonalInformation.DefaultFacetKey,
                            EmailAddressList.DefaultFacetKey,
                            PhoneNumberList.DefaultFacetKey,
                            CustomerFacets.DefaultFacetKey
                        }));
                    }

                    if (contact != null)
                    {
                        var customerFacet = contact.GetFacet <CustomerFacets>(CustomerFacets.DefaultFacetKey);

                        if (customerFacet != null)
                        {
                            // Change facet properties
                            customerFacet.CustomerStatus = customerStatus;
                            //Update facet in contact
                            client.SetFacet(contact, customerFacet);
                        }
                        else
                        {
                            // Facet is new
                            CustomerFacets newCustomerFacet = new CustomerFacets()
                            {
                                CustomerStatus = customerStatus
                            };
                            client.SetFacet(contact, newCustomerFacet);
                        }

                        PersonalInformation existingContactPersonalFacet = contact.GetFacet <PersonalInformation>(PersonalInformation.DefaultFacetKey);
                        if (existingContactPersonalFacet != null)
                        {
                            existingContactPersonalFacet.FirstName = firstName;
                            existingContactPersonalFacet.LastName  = lastName;
                            client.SetFacet(contact, PersonalInformation.DefaultFacetKey, existingContactPersonalFacet);
                        }
                        else
                        {
                            PersonalInformation newPersonalFacet = new PersonalInformation()
                            {
                                FirstName = firstName,
                                LastName  = lastName
                            };
                            client.SetFacet(contact, PersonalInformation.DefaultFacetKey, newPersonalFacet);
                        }

                        PhoneNumberList existingContactPhonFacet = contact.GetFacet <PhoneNumberList>(PhoneNumberList.DefaultFacetKey);
                        if (existingContactPhonFacet != null)
                        {
                            existingContactPhonFacet.PreferredPhoneNumber = new PhoneNumber(countryCode, mobileNumber);
                            existingContactPhonFacet.PreferredKey         = "Mobile";
                            client.SetFacet(contact, PhoneNumberList.DefaultFacetKey, existingContactPhonFacet);
                        }
                        else
                        {
                            PhoneNumberList newContactPhonFacet = new PhoneNumberList(new PhoneNumber(countryCode, mobileNumber), "Mobile");
                            client.SetFacet(contact, PhoneNumberList.DefaultFacetKey, newContactPhonFacet);
                        }

                        await client.SubmitAsync();
                    }

                    Console.ReadLine();
                }
                catch (XdbExecutionException ex)
                {
                    // Deal with exception
                }
            }
        }
        /// <summary>
        /// Get Event Subscriptions Get the list of events subscribed for
        /// </summary>
        /// <exception cref="com.telstra.eventdetection.Client.ApiException">Thrown when fails to make API call</exception>
        /// <param name="body">List of subscribed phone numbers</param>
        /// <returns>Task of ApiResponse (GetSubscriptionResponse)</returns>
        public async System.Threading.Tasks.Task <ApiResponse <GetSubscriptionResponse> > GetSubscriptionAsyncWithHttpInfo(PhoneNumberList body)
        {
            // verify the required parameter 'body' is set
            if (body == null)
            {
                throw new ApiException(400, "Missing required parameter 'body' when calling GetSubscriptionApi->GetSubscription");
            }

            var    localVarPath         = "/v1/eventdetection/events/subscriptions";
            var    localVarPathParams   = new Dictionary <String, String>();
            var    localVarQueryParams  = new List <KeyValuePair <String, String> >();
            var    localVarHeaderParams = new Dictionary <String, String>(Configuration.DefaultHeader);
            var    localVarFormParams   = new Dictionary <String, String>();
            var    localVarFileParams   = new Dictionary <String, FileParameter>();
            Object localVarPostBody     = null;

            // to determine the Content-Type header
            String[] localVarHttpContentTypes = new String[] {
                "application/json"
            };
            String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);

            // to determine the Accept header
            String[] localVarHttpHeaderAccepts = new String[] {
                "application/json"
            };
            String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);

            if (localVarHttpHeaderAccept != null)
            {
                localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
            }

            if (body != null && body.GetType() != typeof(byte[]))
            {
                localVarPostBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter
            }
            else
            {
                localVarPostBody = body; // byte array
            }

            // authentication (auth) required
            // oauth required
            if (!String.IsNullOrEmpty(Configuration.AccessToken))
            {
                localVarHeaderParams["Authorization"] = "Bearer " + Configuration.AccessToken;
            }

            // make the HTTP request
            IRestResponse localVarResponse = (IRestResponse)await Configuration.ApiClient.CallApiAsync(localVarPath,
                                                                                                       Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
                                                                                                       localVarPathParams, localVarHttpContentType);

            int localVarStatusCode = (int)localVarResponse.StatusCode;

            if (ExceptionFactory != null)
            {
                Exception exception = ExceptionFactory("GetSubscription", localVarResponse);
                if (exception != null)
                {
                    throw exception;
                }
            }

            return(new ApiResponse <GetSubscriptionResponse>(localVarStatusCode,
                                                             localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
                                                             (GetSubscriptionResponse)Configuration.ApiClient.Deserialize(localVarResponse, typeof(GetSubscriptionResponse))));
        }
        /// <summary>
        /// Get Event Subscriptions Get the list of events subscribed for
        /// </summary>
        /// <exception cref="com.telstra.eventdetection.Client.ApiException">Thrown when fails to make API call</exception>
        /// <param name="body">List of subscribed phone numbers</param>
        /// <returns>Task of GetSubscriptionResponse</returns>
        public async System.Threading.Tasks.Task <GetSubscriptionResponse> GetSubscriptionAsync(PhoneNumberList body)
        {
            ApiResponse <GetSubscriptionResponse> localVarResponse = await GetSubscriptionAsyncWithHttpInfo(body);

            return(localVarResponse.Data);
        }
        /// <summary>
        /// Get Event Subscriptions Get the list of events subscribed for
        /// </summary>
        /// <exception cref="com.telstra.eventdetection.Client.ApiException">Thrown when fails to make API call</exception>
        /// <param name="body">List of subscribed phone numbers</param>
        /// <returns>GetSubscriptionResponse</returns>
        public GetSubscriptionResponse GetSubscription(PhoneNumberList body)
        {
            ApiResponse <GetSubscriptionResponse> localVarResponse = GetSubscriptionWithHttpInfo(body);

            return(localVarResponse.Data);
        }
        public async Task <bool> CreateContact(
            string source,
            string identifier,
            string firstName,
            string lastName,
            string title,
            string phone,
            string email)
        {
            using (XConnectClient client = GetClient())
            {
                try
                {
                    IdentifiedContactReference reference = new IdentifiedContactReference(source, identifier);

                    var contactTask = client.GetAsync <Contact>(
                        reference,
                        new ContactExpandOptions(
                            PersonalInformation.DefaultFacetKey,
                            EmailAddressList.DefaultFacetKey,
                            PhoneNumberList.DefaultFacetKey,
                            Pet.DefaultFacetKey)
                        );

                    Contact existingContact = await contactTask;

                    if (existingContact != null)
                    {
                        return(false);
                    }

                    var contactIdentifier = new[]
                    {
                        new ContactIdentifier(source, identifier, ContactIdentifierType.Known)
                    };

                    Contact contact = new Contact(contactIdentifier);

                    var personal = new PersonalInformation
                    {
                        FirstName = firstName,
                        LastName  = lastName,
                        Title     = title
                    };

                    var preferredPhoneNumber = new PhoneNumber(string.Empty, phone);
                    var phoneNumbers         = new PhoneNumberList(preferredPhoneNumber, "Work phone");

                    var preferredEmail = new EmailAddress(email, true);
                    var emails         = new EmailAddressList(preferredEmail, "Work email");

                    var petFacet = contact.GetFacet <Pet>(Pet.DefaultFacetKey);

                    if (petFacet == null)
                    {
                        petFacet = new Pet()
                        {
                            Breed = "cat",
                            Name  = "Kitty"
                        };
                    }

                    client.SetFacet <Pet>(contact, petFacet);
                    client.AddContact(contact);
                    client.SetPhoneNumbers(contact, phoneNumbers);
                    client.SetPersonal(contact, personal);
                    client.SetEmails(contact, emails);

                    Interaction interaction = new Interaction(contact, InteractionInitiator.Brand, Guid.NewGuid(), "test");
                    var         ev          = new PageViewEvent(DateTime.UtcNow, Guid.Parse("{11111111-1111-1111-1111-111111111111}"), 1, "en");
                    interaction.Events.Add(ev);

                    client.AddInteraction(interaction);

                    await client.SubmitAsync();

                    return(true);
                }
                catch (XdbExecutionException ex)
                {
                    return(false);
                }
            }
        }
Beispiel #28
0
        public ReadonlyContact CreateContact(Guid contactId, Classification classification, EngagementMeasures engagementMeasures, PersonalInformation personalInfo, EmailAddressList emailAddressList, PhoneNumberList phoneNumberList, AddressList addressList, SalesforceContactInformation salseforceContactInformation, CustomSalesforceContactInformation customSalseforceContactInformation, List <ContactIdentifier> identifiers)
        {
            int      classification1 = 0;
            int      visitCount      = 0;
            int      totalValue      = 0;
            string   firstName       = string.Empty;
            string   middleName      = string.Empty;
            string   surname         = string.Empty;
            string   title           = string.Empty;
            string   suffix          = string.Empty;
            string   nickname        = string.Empty;
            DateTime?birthDate       = new DateTime?();
            string   gender          = string.Empty;
            string   jobTitle        = string.Empty;
            string   salesforceContactCreatedDate  = string.Empty;
            string   customSalesforceJourneyStatus = string.Empty;
            KeyValuePair <string, IAddress>               preferredAddress      = new KeyValuePair <string, IAddress>();
            KeyValuePair <string, IEmailAddress>          preferredEmailAddress = new KeyValuePair <string, IEmailAddress>();
            KeyValuePair <string, IPhoneNumber>           preferredPhoneNumber  = new KeyValuePair <string, IPhoneNumber>();
            IList <KeyValuePair <string, IAddress> >      addresses             = (IList <KeyValuePair <string, IAddress> >) new List <KeyValuePair <string, IAddress> >();
            IList <KeyValuePair <string, IEmailAddress> > emailAddresses        = (IList <KeyValuePair <string, IEmailAddress> >) new List <KeyValuePair <string, IEmailAddress> >();
            IList <KeyValuePair <string, IPhoneNumber> >  phoneNumbers          = (IList <KeyValuePair <string, IPhoneNumber> >) new List <KeyValuePair <string, IPhoneNumber> >();

            if (classification != null)
            {
                classification1 = classification.OverrideClassificationLevel > 0 ? classification.OverrideClassificationLevel : classification.ClassificationLevel;
            }
            if (engagementMeasures != null)
            {
                visitCount = engagementMeasures.TotalInteractionCount;
                totalValue = engagementMeasures.TotalValue;
            }
            List <ContactIdentifier> identifiers1 = identifiers != null ? identifiers : new List <ContactIdentifier>();

            if (personalInfo != null)
            {
                firstName  = personalInfo.FirstName;
                middleName = personalInfo.MiddleName;
                surname    = personalInfo.LastName;
                gender     = personalInfo.Gender;
                birthDate  = personalInfo.Birthdate;
                jobTitle   = personalInfo.JobTitle;
                nickname   = personalInfo.Nickname;
                suffix     = personalInfo.Suffix;
                title      = personalInfo.Title;
            }
            if (emailAddressList != null)
            {
                preferredEmailAddress = emailAddressList.PreferredEmail == null || string.IsNullOrEmpty(emailAddressList.PreferredEmail.SmtpAddress) ? new KeyValuePair <string, IEmailAddress>(string.Empty, (IEmailAddress)null) : new KeyValuePair <string, IEmailAddress>(emailAddressList.PreferredKey, (IEmailAddress) new ReadonlyEmailAddress(emailAddressList.PreferredEmail));
                emailAddresses        = (IList <KeyValuePair <string, IEmailAddress> >)emailAddressList.Others.Keys.Select <string, KeyValuePair <string, IEmailAddress> >((Func <string, KeyValuePair <string, IEmailAddress> >)(key => new KeyValuePair <string, IEmailAddress>(key, (IEmailAddress) new ReadonlyEmailAddress(emailAddressList.Others[key])))).OrderBy <KeyValuePair <string, IEmailAddress>, string>((Func <KeyValuePair <string, IEmailAddress>, string>)(kvp => kvp.Key)).ToList <KeyValuePair <string, IEmailAddress> >();
            }
            if (addressList != null)
            {
                preferredAddress = addressList.PreferredAddress == null || string.IsNullOrEmpty(addressList.PreferredKey) ? new KeyValuePair <string, IAddress>(string.Empty, (IAddress)null) : new KeyValuePair <string, IAddress>(addressList.PreferredKey, (IAddress) new ReadonlyAddress(addressList.PreferredAddress));
                addresses        = (IList <KeyValuePair <string, IAddress> >)addressList.Others.Keys.Select <string, KeyValuePair <string, IAddress> >((Func <string, KeyValuePair <string, IAddress> >)(key => new KeyValuePair <string, IAddress>(key, (IAddress) new ReadonlyAddress(addressList.Others[key])))).OrderBy <KeyValuePair <string, IAddress>, string>((Func <KeyValuePair <string, IAddress>, string>)(kvp => kvp.Key)).ToList <KeyValuePair <string, IAddress> >();
            }
            if (phoneNumberList != null)
            {
                preferredPhoneNumber = phoneNumberList.PreferredPhoneNumber == null || string.IsNullOrEmpty(phoneNumberList.PreferredKey) ? new KeyValuePair <string, IPhoneNumber>(string.Empty, (IPhoneNumber)null) : new KeyValuePair <string, IPhoneNumber>(phoneNumberList.PreferredKey, (IPhoneNumber) new ReadonlyPhoneNumber(phoneNumberList.PreferredPhoneNumber));
                phoneNumbers         = (IList <KeyValuePair <string, IPhoneNumber> >)phoneNumberList.Others.Keys.Select <string, KeyValuePair <string, IPhoneNumber> >((Func <string, KeyValuePair <string, IPhoneNumber> >)(key => new KeyValuePair <string, IPhoneNumber>(key, (IPhoneNumber) new ReadonlyPhoneNumber(phoneNumberList.Others[key])))).OrderBy <KeyValuePair <string, IPhoneNumber>, string>((Func <KeyValuePair <string, IPhoneNumber>, string>)(kvp => kvp.Key)).ToList <KeyValuePair <string, IPhoneNumber> >();
            }
            if (salseforceContactInformation != null)
            {
                salesforceContactCreatedDate = salseforceContactInformation.CreatedDate.ToLongDateString();
            }
            if (customSalseforceContactInformation != null)
            {
                customSalesforceJourneyStatus = customSalseforceContactInformation.WelcomeJourneyStatus;
            }
            return(new ExperienceProfileSalesforceReadonlyContact(contactId, classification1, identifiers1, firstName, middleName, surname, title, suffix, nickname, birthDate, gender, jobTitle, totalValue, visitCount, preferredAddress, preferredEmailAddress, preferredPhoneNumber, addresses, emailAddresses, phoneNumbers, salesforceContactCreatedDate, customSalesforceJourneyStatus));
        }
        private static async Task CreateContacts(XConnectClientConfiguration xConfig, string firstName, string lastName, string email, string countryCode, string mobileNumber, string customerStatus)
        {
            DateTime DateOfBirth = new DateTime(1947, 12, 9);

            // Initialize a client using the validated configuration
            using (var client = new XConnectClient(xConfig))
            {
                try
                {
                    IdentifiedContactReference reference = new IdentifiedContactReference("CustomerRef", email);
                    Contact existingContact = client.Get <Contact>(reference, new ContactExpandOptions(new string[] {
                        PersonalInformation.DefaultFacetKey,
                        EmailAddressList.DefaultFacetKey,
                        PhoneNumberList.DefaultFacetKey,
                        CustomerFacets.DefaultFacetKey
                    }));

                    if (existingContact != null)
                    {
                        Console.WriteLine("This contact already exists.Please run the update option.");
                    }
                    else
                    {
                        var identifiers = new ContactIdentifier[]
                        {
                            new ContactIdentifier("CustomerRef", $"{email}", ContactIdentifierType.Known)
                        };

                        // Create a new contact with the identifier
                        Contact newContact = new Contact(identifiers);

                        PersonalInformation personalInfoFacet = new PersonalInformation();
                        personalInfoFacet.FirstName = firstName;
                        personalInfoFacet.LastName  = lastName;
                        personalInfoFacet.Birthdate = DateOfBirth;

                        client.SetFacet <PersonalInformation>(newContact, PersonalInformation.DefaultFacetKey, personalInfoFacet);

                        EmailAddressList newEmailFacet = new EmailAddressList(new EmailAddress(email, true), "Work");
                        client.SetFacet <EmailAddressList>(newContact, newEmailFacet);

                        PhoneNumberList newPhoneFacet = new PhoneNumberList(new PhoneNumber(countryCode, mobileNumber), "Mobile");
                        client.SetFacet <PhoneNumberList>(newContact, newPhoneFacet);

                        CustomerFacets customerFacets = new CustomerFacets();
                        customerFacets.CustomerStatus = customerStatus;
                        client.SetFacet <CustomerFacets>(newContact, CustomerFacets.DefaultFacetKey, customerFacets);

                        client.AddContact(newContact);

                        // Submit contact
                        await client.SubmitAsync();

                        // Get the last batch that was executed
                        var operations = client.LastBatch;

                        Console.WriteLine("RESULTS...");

                        //// Loop through operations and check status
                        foreach (var operation in operations)
                        {
                            Console.WriteLine(operation.OperationType + operation.Target.GetType().ToString() + " Operation: " + operation.Status);
                        }
                    }
                }
                catch (XdbExecutionException ex)
                {
                    // Deal with exception
                }
            }
        }
        public async Task <bool> UpdateContactInformation(
            Guid contactId,
            string firstName,
            string middleName,
            string lastName,
            string title,
            string jobTitle,
            string phone,
            string email,
            string gender,
            byte[] avatar = null)
        {
            using (XConnectClient client = GetClient())
            {
                try
                {
                    ContactReference reference = new ContactReference(contactId);

                    var contactTask = client.GetAsync <Contact>(
                        reference,
                        new ContactExpandOptions(
                            PersonalInformation.DefaultFacetKey,
                            EmailAddressList.DefaultFacetKey,
                            PhoneNumberList.DefaultFacetKey,
                            Avatar.DefaultFacetKey)
                        );

                    Contact contact = await contactTask;

                    if (contact == null)
                    {
                        return(false);
                    }

                    var personal = contact.Personal();

                    if (personal == null)
                    {
                        personal = new PersonalInformation();
                    }

                    personal.FirstName  = firstName;
                    personal.MiddleName = middleName;
                    personal.LastName   = lastName;
                    personal.Title      = title;
                    personal.JobTitle   = jobTitle;
                    personal.Gender     = gender;

                    var phoneNumbers         = contact.PhoneNumbers();
                    var preferredPhoneNumber = new PhoneNumber(string.Empty, phone);

                    if (phoneNumbers == null)
                    {
                        phoneNumbers = new PhoneNumberList(preferredPhoneNumber, "Work phone");
                    }
                    else
                    {
                        phoneNumbers.PreferredPhoneNumber = preferredPhoneNumber;
                    }

                    var emails         = contact.Emails();
                    var preferredEmail = new EmailAddress(email, true);

                    if (emails == null)
                    {
                        emails = new EmailAddressList(preferredEmail, "Work email");
                    }
                    else
                    {
                        emails.PreferredEmail = preferredEmail;
                    }

                    if (avatar != null)
                    {
                        var avatarFacet = contact.Avatar();

                        if (avatarFacet == null)
                        {
                            avatarFacet = new Avatar("image/jpeg", avatar);
                        }
                        else
                        {
                            avatarFacet.Picture = avatar;
                        }

                        client.SetAvatar(contact, avatarFacet);
                    }

                    client.SetPhoneNumbers(contact, phoneNumbers);
                    client.SetPersonal(contact, personal);
                    client.SetEmails(contact, emails);

                    await client.SubmitAsync();

                    return(true);
                }
                catch (XdbExecutionException ex)
                {
                    return(false);
                }
            }
        }