Example #1
0
        private static void AddInteraction(
            IXdbContext client, Contact contact, IEnumerable <Guid> goalIds,
            IEnumerable <Guid> outcomeIds, IEnumerable <Guid> eventIds, Guid campaignId)
        {
            var interaction = new Interaction(contact, InteractionInitiator.Brand, SystemChannelId, UserAgent);

            foreach (Guid goalId in goalIds)
            {
                var goal = new Goal(goalId, DateTime.UtcNow)
                {
                    Duration = new TimeSpan(0, 0, 30)
                };
                interaction.Events.Add(goal);
            }

            foreach (Guid outcomeId in outcomeIds)
            {
                var outcome = new Outcome(outcomeId, DateTime.UtcNow, "usd", 100.00m);
                interaction.Events.Add(outcome);
            }

            foreach (Guid eventId in eventIds)
            {
                var pageEvent = new Event(eventId, DateTime.UtcNow)
                {
                    Duration = new TimeSpan(0, 0, 30)
                };
                interaction.Events.Add(pageEvent);
            }

            interaction.CampaignId = campaignId;

            client.AddInteraction(interaction);
        }
        public bool AddContactIdentifier(Contact contact, string identifierName, string identifierValue)
        {
            using (var client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
            {
                try
                {
                    if (contact == null)
                    {
                        // Get from current contact
                        var trackerIdentifier = new IdentifiedContactReference(
                            Sitecore.Analytics.XConnect.DataAccess.Constants.IdentifierSource,
                            Sitecore.Analytics.Tracker.Current.Contact.ContactId.ToString("N"));
                        contact = client.Get <Contact>(trackerIdentifier,
                                                       new ContactExpandOptions(Avatar.DefaultFacetKey));
                    }

                    client.AddContactIdentifier(contact,
                                                new ContactIdentifier(identifierName, identifierValue,
                                                                      ContactIdentifierType.Known));
                    client.Submit();

                    return(true);
                }
                catch (XdbExecutionException ex)
                {
                    // Manage exception
                    Sitecore.Diagnostics.Log.Error(
                        $"[FaceLogin] Error adding identifier {identifierName}='{identifierValue}'",
                        ex, ex.GetType());
                    return(false);
                }
            }
        }
        public bool UpdateContactConsent(Contact contact, bool consent)
        {
            using (var client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
            {
                try
                {
                    // Retrieve contact
                    if (contact == null)
                    {
                        return(false);
                    }

                    // Retrieve facet (or create one)
                    var facet = contact.GetFacet <AdhereToFaceLoginFacet>(AdhereToFaceLoginFacet.DefaultFacetKey) ??
                                new AdhereToFaceLoginFacet();

                    // Change facet properties
                    facet.FaceRecognitionAllowed = consent;

                    // Set the updated facet
                    client.SetFacet(contact, AdhereToFaceLoginFacet.DefaultFacetKey, facet);
                    client.Submit();
                    return(true);
                }
                catch (XdbExecutionException ex)
                {
                    // Manage exception
                    Sitecore.Diagnostics.Log.Error(
                        $"[Bookshelf] Error updating avatar.",
                        ex, ex.GetType());
                    return(false);
                }
            }
        }
        /// <summary>
        /// Set emotion facet to contact
        /// </summary>
        /// <param name="contact">Contact to be updated</param>
        /// <param name="facet">Facet to be applied to Contact</param>
        public void SetEmotionFacet(Contact contact, EmotionFacet facet)
        {
            using (var client = SitecoreXConnectClientConfiguration.GetClient())
            {
                try
                {
                    var emotions = contact.GetFacet <EmotionFacet>(EmotionFacet.DefaultFacetKey);
                    if (emotions == null)
                    {
                        client.SetFacet(contact, EmotionFacet.DefaultFacetKey, facet);
                    }
                    else
                    {
                        UpdateFacetValues(facet, emotions);
                        client.SetFacet(contact, EmotionFacet.DefaultFacetKey, emotions);
                    }

                    client.Submit();
                }
                catch (XdbExecutionException ex)
                {
                    Log.Error($"Could not set facet for {contact.Id} contact", ex, this);
                }
            }
        }
        private void CreateInteraction(Contact contact, Guid goalId, string goalData)
        {
            using (Sitecore.XConnect.Client.XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
            {
                try
                {
                    var newContact = new Sitecore.XConnect.Contact();
                    client.AddContact(newContact);

                    // Create new interaction for this contact
                    Guid   channelId   = Guid.NewGuid(); // Replace with channel ID from Sitecore
                    string userAgent   = "Mozilla/5.0 (Nintendo Switch; ShareApplet) AppleWebKit/601.6 (KHTML, like Gecko) NF/4.0.0.5.9 NintendoBrowser/5.1.0.13341";
                    var    interaction = new Sitecore.XConnect.Interaction(newContact, InteractionInitiator.Brand, channelId, userAgent);


                    // Create new instance of goal
                    Sitecore.XConnect.Goal goal = new Goal(goalId, DateTime.UtcNow);
                    {
                    };
                    goal.Data = goalData;
                    // Add goal to interaction
                    interaction.Events.Add(goal);

                    // Add interaction operation to client
                    client.AddInteraction(interaction);

                    // Submit interaction
                    client.Submit();
                }
                catch (Exception ex)
                {
                    // Handle exception
                }
            }
        }
Example #6
0
        public Sitecore.XConnect.Contact CreateContact(string email)
        {
            var reference = new ContactIdentifier("emailaddress", email, ContactIdentifierType.Known);
            var contact   = new Sitecore.XConnect.Contact(reference);

            return(contact);
        }
        public bool UpdateContactPersonal(Contact contact, string firstName, string lastName)
        {
            using (var client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
            {
                try
                {
                    // Retrieve contact
                    if (contact == null)
                    {
                        return(false);
                    }

                    // Retrieve facet (or create one)
                    var facet = contact.GetFacet <PersonalInformation>(PersonalInformation.DefaultFacetKey) ??
                                new PersonalInformation();

                    // Change facet properties
                    facet.FirstName = firstName;
                    facet.LastName  = lastName;

                    // Set the updated facet
                    client.SetFacet(contact, PersonalInformation.DefaultFacetKey, facet);
                    client.Submit();
                    return(true);
                }
                catch (XdbExecutionException ex)
                {
                    // Manage exception
                    Sitecore.Diagnostics.Log.Error(
                        $"[FaceLogin] Error saving contact.",
                        ex, ex.GetType());
                    return(false);
                }
            }
        }
Example #8
0
        public JsonResult GetContactHubspotData(string contactId)
        {
            using (XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
            {
                try
                {
                    Sitecore.XConnect.Contact contact = client.Get <Sitecore.XConnect.Contact>(new ContactReference(new Guid(contactId)),
                                                                                               new ContactExpandOptions(ScoreFacet.DefaultFacetKey, ScoreNameFacet.DefaultFacetKey)
                    {
                    });

                    if (contact != null)
                    {
                        // For each contact, retrieve the facet - will return null if contact does not have this facet set
                        var facetValue = contact.GetFacet <ScoreFacet>(ScoreFacet.DefaultFacetKey);
                        var facetName  = contact.GetFacet <ScoreNameFacet>(ScoreNameFacet.DefaultFacetKey);

                        if (facetValue != null && facetValue != null)
                        {
                            return(Json(new Tuple <string, int>(facetName.HubspotScoreName, facetValue.HubspotScore), JsonRequestBehavior.AllowGet));
                        }
                    }
                }
                catch (XdbExecutionException ex)
                {
                    // Handle exceptions
                }
            }
            return(null);
        }
Example #9
0
        private void AddProfileScore(IXdbContext client, Contact contact)
        {
            if (string.IsNullOrWhiteSpace(tbProfileScore.Text) || string.IsNullOrWhiteSpace(tbProfileKeyId.Text) || string.IsNullOrWhiteSpace(tbProfileId.Text))
            {
                return;
            }

            Guid profileId    = Guid.Parse(tbProfileId.Text);
            Guid profileKeyId = Guid.Parse(tbProfileKeyId.Text);
            int  score        = int.Parse(tbProfileScore.Text, CultureInfo.CurrentCulture);

            var interaction          = new Interaction(contact, InteractionInitiator.Brand, SystemChannelId, UserAgent);
            var engagementValueEvent = new Event(ProfileScoreChangeEventDefinitionId, DateTime.UtcNow);

            interaction.Events.Add(engagementValueEvent);
            client.AddInteraction(interaction);

            var profileScores = new ProfileScores();
            var profileScore  = new ProfileScore
            {
                Values =
                {
                    [profileKeyId] = score
                }
            };

            profileScores.Scores.Add(profileId, profileScore);
            client.SetProfileScores(interaction, profileScores);
        }
Example #10
0
        private void CreateContacts()
        {
            using (IXdbContext client = _xConnectClientFactory.GetXConnectClient())
            {
                try
                {
                    var numberOfContacts = int.Parse(tbNumberOfContacts.Text, CultureInfo.CurrentCulture);

                    var goalIds    = tbGoalIds.Text.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(Guid.Parse);
                    var eventIds   = tbEventIds.Text.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(Guid.Parse);
                    var outcomeIds = tbOutcomeIds.Text.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(Guid.Parse);

                    var listId     = !string.IsNullOrWhiteSpace(tbListId.Text) ? Guid.Parse(tbListId.Text) : Guid.Empty;
                    var campaignId = !string.IsNullOrWhiteSpace(tbCampaignId.Text) ? Guid.Parse(tbCampaignId.Text) : Guid.Empty;

                    for (var i = 0; i < numberOfContacts; i++)
                    {
                        string email = GetEmailAddress(i);

                        var contact = new Contact(new ContactIdentifier("ListManager", email, ContactIdentifierType.Known));

                        client.AddContact(contact);

                        AddPreferredEmail(i, client, contact, email);

                        AddPhoneNumber(client, contact, tbPhoneNumber.Text);

                        AddPersonalInfo(client, contact, tbPreferredLanguage.Text);

                        AddListSubscription(listId, client, contact);

                        AddConsentInformation(client, contact);

                        AddProfileScore(client, contact);

                        AddEngagementValue(client, contact);

                        AddInteraction(client, contact, goalIds, outcomeIds, eventIds, campaignId);

                        if (i % 10 != 0)
                        {
                            continue;
                        }

                        var numberOfContactsBeingSubmitted = i / 1 > 0 ? i / 1 : 1;

                        Logger.Info($"Submitting {numberOfContactsBeingSubmitted} contacts", this);
                        client.Submit();
                    }

                    client.Submit();
                }
                catch (Exception ex)
                {
                    Logger.Error("Failed to submit contacts", ex, this);
                }
            }
        }
Example #11
0
        private void AddPhoneNumber(IXdbContext client, Contact contact, string text)
        {
            if (string.IsNullOrWhiteSpace(text))
            {
                return;
            }

            client.SetPhoneNumbers(contact, new PhoneNumberList(new PhoneNumber("0045", text), "Preferred"));
        }
Example #12
0
 private void AddConsentInformation(IXdbContext client, Contact contact)
 {
     if (checkBoxConsentRevoked.Checked || checkBoxDoNotMarket.Checked)
     {
         client.SetConsentInformation(contact, new ConsentInformation()
         {
             ConsentRevoked = checkBoxConsentRevoked.Checked,
             DoNotMarket    = checkBoxDoNotMarket.Checked
         });
     }
 }
 private static void MakeContactKnown(IXdbContext client, Contact contact)
 {
     if (contact.IsKnown)
     {
         return;
     }
     if (!Sitecore.Configuration.Settings.GetBoolSetting("MakeContactKnownOnFormsUpdate", true))
     {
         return;
     }
     client.AddContactIdentifier(contact, new ContactIdentifier("scformsextension-known", Guid.NewGuid().ToString("N"), ContactIdentifierType.Known));
 }
        /// <summary>
        /// Gets a contact from the xDb using xConnect
        /// </summary>
        /// <param name="contactId"></param>
        /// <returns></returns>
        public Contact GetContact(string contactId)
        {
            var reference = new ContactReference(Guid.Parse(contactId));

            Sitecore.XConnect.Contact xConnectContact = Client.Get(reference, new ContactExpandOptions()
            {
            });

            // TO DO: If there are any other fields to add

            return(xConnectContact);
        }
Example #15
0
        public void RegisterGoal(Guid channelID, Guid goalID, string userAgent)
        {
            using (Sitecore.XConnect.Client.XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
            {
                try
                {
                    // var contact = new Sitecore.XConnect.Contact();
                    //Guid channelID = Guid.NewGuid();
                    //string userAgent = "Sample User Agent";

                    //string globalCookie = Request.Cookies["SC_ANALYTICS_GLOBAL_COOKIE"].Value;
                    //var reference = new IdentifiedContactReference(Sitecore.XConnect.Constants.AliasIdentifierSource, globalCookie.Split('|')[0]);

                    string trackerID = Sitecore.Analytics.Tracker.Current.Contact.ContactId.ToString();

                    //var reference = new IdentifiedContactReference(Sitecore.XConnect.Constants.AliasIdentifierSource,trackerID);
                    var reference = new IdentifiedContactReference("xDB.Tracker", trackerID);

                    Sitecore.XConnect.Contact contact = client.Get <Sitecore.XConnect.Contact>(reference, new ContactExpandOptions()
                    {
                    });

                    if (contact == null)
                    {
                        contact = new Sitecore.XConnect.Contact();
                    }

                    var interaction = new Sitecore.XConnect.Interaction(contact, InteractionInitiator.Brand, channelID, userAgent);

                    // Guid goalID = Guid.Parse("{9B6DC6A2-EB41-47B5-B10F-39AC37DE214F}"); // ID of goal item

                    var goal = new Goal(goalID, DateTime.UtcNow);

                    goal.EngagementValue = 20; // Manually setting engagement value rather than going to defintion item

                    interaction.Events.Add(goal);



                    client.AddContact(contact);
                    client.AddInteraction(interaction);

                    client.Submit();
                }
                catch (XdbExecutionException ex)
                {
                    // Handle exception
                }
            }
        }
Example #16
0
        private static void AddPersonalInfo(IXdbContext client, Contact contact, string preferredLanguage = null)
        {
            var personalInformation = new PersonalInformation
            {
                FirstName = Name.First(),
                LastName  = Name.Last(),
            };

            if (!string.IsNullOrWhiteSpace(preferredLanguage))
            {
                personalInformation.PreferredLanguage = preferredLanguage;
            }

            client.SetPersonal(contact, personalInformation);
        }
Example #17
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void OnClick_LoadContact(object sender, EventArgs e)
        {
            using (var client = _xConnectClientFactory.GetXConnectClient())
            {
                try
                {
                    ContactReference           contactReference           = null;
                    IdentifiedContactReference identifiedContactReference = null;

                    identifiedContactReference = new IdentifiedContactReference("ListManager", tbContactIdentifierValue.Text);

                    var selectedFacetKeys = new List <string>();
                    foreach (ListItem lbFacetsItem in lbFacets.Items)
                    {
                        if (lbFacetsItem.Selected)
                        {
                            selectedFacetKeys.Add(lbFacetsItem.Value);
                        }
                    }

                    Contact contact = client.Get((IEntityReference <Contact>)contactReference ?? identifiedContactReference, new ContactExpandOptions(selectedFacetKeys.ToArray())
                    {
                        Interactions = new RelatedInteractionsExpandOptions()
                        {
                            StartDateTime = DateTime.MinValue,
                            Limit         = int.MaxValue
                        }
                    });

                    var serializerSettings = new JsonSerializerSettings
                    {
                        ContractResolver = new XdbJsonContractResolver(client.Model,
                                                                       serializeFacets: chkIncludeFacets.Checked,
                                                                       serializeContactInteractions: chkIncludeInteractions.Checked),
                        DateTimeZoneHandling = DateTimeZoneHandling.Utc,
                        DefaultValueHandling = DefaultValueHandling.Ignore,
                        Formatting           = Formatting.Indented
                    };

                    Json          = JsonConvert.SerializeObject(contact, serializerSettings);
                    lblError.Text = string.Empty;
                }
                catch (Exception ex)
                {
                    lblError.Text = ex.ToString();
                }
            }
        }
        /// <summary>
        /// Inserts a contact into xDb using xConnect
        /// </summary>
        /// <param name="contact"></param>
        /// <returns></returns>
        public bool InsertContactAndAddContactToList(string source, string contactId, string alias, string firstName, string lastName, string title, string emailAddress, string listId)
        {
            // Identifier for a 'known' contact
            var identifier = new ContactIdentifier[]
            {
                new ContactIdentifier(source, contactId, ContactIdentifierType.Known),
                new ContactIdentifier(source + "_ALIAS", alias, ContactIdentifierType.Known)
            };

            // Create a new contact with the identifier
            var knownContact = new Sitecore.XConnect.Contact(identifier);

            var personalInfoFacet = new PersonalInformation()
            {
                Title     = title,
                FirstName = firstName,
                LastName  = lastName
            };


            Client.SetPersonal(knownContact, personalInfoFacet);

            var emailAddressList = new EmailAddressList(new EmailAddress(emailAddress, false), "SlackEmailAddress");

            Client.SetEmails(knownContact, emailAddressList);

            // if contact does not have list subscriptions then we need to add it
            if (knownContact.ListSubscriptions() == null)
            {
                var listSubscriptions = new ListSubscriptions();
                listSubscriptions.Subscriptions.Add(new ContactListSubscription(DateTime.Now, true, new Guid(listId)));
                Client.SetFacet <ListSubscriptions>(knownContact, ListSubscriptions.DefaultFacetKey, listSubscriptions);
            }
            else
            {
                knownContact.ListSubscriptions().Subscriptions.Add(new ContactListSubscription(DateTime.Now, true, new Guid(listId)));
            }

            Client.AddContact(knownContact);

            Client.Submit();

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

            return(true);
        }
Example #19
0
 private static void AddListSubscription(Guid listId, IXdbContext client, Contact contact)
 {
     if (listId != Guid.Empty)
     {
         client.SetListSubscriptions(contact, new ListSubscriptions()
         {
             Subscriptions = new List <ContactListSubscription>()
             {
                 // 9.1 only
                 //new ContactListSubscription(DateTime.UtcNow, true, listId)
                 //{
                 //    SourceDefinitionId = KnownIdentifiers.EmailExperienceManagerSubscriptionId
                 //}
             }
         });
     }
 }
Example #20
0
        private async static Task <Contact> CreateOrUpdateContact(XConnectClient client)
        {
            var identifiedContactReference = new IdentifiedContactReference(_fakeContact.Source, _fakeContact.EmailAddress);

            var options = new ContactExpandOptions(PersonalInformation.DefaultFacetKey, EmailAddressList.DefaultFacetKey, AddressList.DefaultFacetKey, PhoneNumberList.DefaultFacetKey, Avatar.DefaultFacetKey);

            Task <Contact> contactTask = client.GetAsync <Contact>(identifiedContactReference, options);
            Contact        contact     = await contactTask;

            if (contact == null)
            {
                contact = new Sitecore.XConnect.Contact(new Sitecore.XConnect.ContactIdentifier(_fakeContact.Source, _fakeContact.EmailAddress, Sitecore.XConnect.ContactIdentifierType.Known));
                client.AddContact(contact);
            }

            return(contact);
        }
Example #21
0
        private void AddEngagementValue(IXdbContext client, Contact contact)
        {
            if (string.IsNullOrWhiteSpace(tbEngagementValue.Text))
            {
                return;
            }

            int engagementValue = int.Parse(tbEngagementValue.Text, CultureInfo.CurrentCulture);

            var interaction          = new Interaction(contact, InteractionInitiator.Brand, SystemChannelId, UserAgent);
            var engagementValueEvent = new Event(Guid.NewGuid(), DateTime.UtcNow)
            {
                EngagementValue = engagementValue
            };

            interaction.Events.Add(engagementValueEvent);

            client.AddInteraction(interaction);
        }
        protected override bool Execute(UpdateContactData data, FormSubmitContext formSubmitContext)
        {
            Assert.ArgumentNotNull(data, nameof(data));
            Assert.ArgumentNotNull(formSubmitContext, nameof(formSubmitContext));

            var firstNameField = GetFieldById(data.FirstNameFieldId, formSubmitContext.Fields);
            var lastNameField  = GetFieldById(data.LastNameFieldId, formSubmitContext.Fields);
            var emailField     = GetFieldById(data.EmailFieldId, formSubmitContext.Fields);

            if (firstNameField == null && lastNameField == null && emailField == null)
            {
                return(false);
            }

            using (var client = CreateClient())
            {
                try
                {
                    var source = "Subscribe.Form";
                    var id     = CurrentTracker.Contact.ContactId.ToString("N");

                    CurrentTracker.Session.IdentifyAs(source, id);
                    var trackerIdentifier = new IdentifiedContactReference(source, id);

                    var expandOptions = new ContactExpandOptions(
                        PersonalInformation.DefaultFacetKey,
                        CollectionModel.FacetKeys.EmailAddressList);

                    XConnectContact contact = client.Get(trackerIdentifier, expandOptions);

                    SetPersonalInformation(GetValue(firstNameField), GetValue(lastNameField), contact, client);

                    SetEmail(GetValue(emailField), contact, client);
                    client.Submit();
                    return(true);
                }
                catch (Exception ex)
                {
                    Logger.LogError(ex.Message, ex);
                    return(false);
                }
            }
        }
        private static void SetPersonalInformation(string firsName, string lastName, XConnectContact contact, IXdbContext client)
        {
            if (string.IsNullOrEmpty(firsName) && string.IsNullOrEmpty(lastName))
            {
                return;
            }

            PersonalInformation personalInfoFacet = contact.Personal() ?? new PersonalInformation();

            if (personalInfoFacet.FirstName == firsName && personalInfoFacet.LastName == lastName)
            {
                return;
            }

            personalInfoFacet.FirstName = firsName;
            personalInfoFacet.LastName  = lastName;

            client.SetPersonal(contact, personalInfoFacet);
        }
        public bool UpdateContactAvatar(Contact contact, string avatar)
        {
            using (var client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
            {
                try
                {
                    // Retrieve contact
                    if (contact == null)
                    {
                        return(false);
                    }

                    // Retrieve facet (or create one)
                    var facet = contact.GetFacet <Avatar>(Avatar.DefaultFacetKey);

                    // Change facet properties
                    var byteArray = _imageService.Base64ToByteArray(avatar);
                    if (facet == null)
                    {
                        facet = new Avatar("image/jpeg", byteArray);
                    }
                    else
                    {
                        facet.MimeType = "image/jpeg";
                        facet.Picture  = byteArray;
                    }

                    // Set the updated facet
                    client.SetAvatar(contact, facet);
                    client.Submit();
                    return(true);
                }
                catch (XdbExecutionException ex)
                {
                    // Manage exception
                    Sitecore.Diagnostics.Log.Error(
                        $"[FaceLogin] Error updating avatar.",
                        ex, ex.GetType());
                    return(false);
                }
            }
        }
 public void UpdateOrCreateXDbServiceContactWithEmail(IXDbContactWithEmail serviceContact)
 {
     using (var client = SitecoreXConnectClientConfiguration.GetClient())
     {
         var reference = new IdentifiedContactReference(serviceContact.IdentifierSource, serviceContact.IdentifierValue);
         var contact   = client.Get(reference, new ContactExpandOptions(CollectionModel.FacetKeys.EmailAddressList));
         if (contact == null)
         {
             contact = new Contact(new ContactIdentifier(reference.Source, reference.Identifier, ContactIdentifierType.Known));
             SetEmail(contact, serviceContact, client);
             client.AddContact(contact);
             client.Submit();
         }
         else if (contact.Emails()?.PreferredEmail.SmtpAddress != serviceContact.Email)
         {
             SetEmail(contact, serviceContact, client);
             client.Submit();
         }
     }
 }
 public T GetFacet <T>(Sitecore.XConnect.Contact contact, string FacetKey) where T : Facet
 {
     using (XConnectClient client = SitecoreXConnectClientConfiguration.GetClient())
     {
         try
         {
             return(contact.GetFacet <T>(FacetKey));
         }
         catch (XdbExecutionException ex)
         {
             Log.Error($"XConnectContactRepository: Error reading facet '{FacetKey}' from contact '{contact.Id}'", ex, this);
             return(null);
         }
         catch (Exception ex)
         {
             Log.Error("XConnectContactRepository: Error communication with the xConnect colllection service", ex, this);
             return(null);
         }
     }
 }
Example #27
0
        public Sitecore.XConnect.Contact GetContact(string email)
        {
            try
            {
                using (Sitecore.XConnect.Client.XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
                {
                    try
                    {
                        if (IsContactInSession(email))
                        {
                            var reference = new Sitecore.XConnect.ContactReference(Tracker.Current.Session.Contact.ContactId);

                            var contact = client.Get(reference, new Sitecore.XConnect.ContactExpandOptions()
                            {
                            });

                            return(contact);
                        }

                        // Retrieve contact
                        Sitecore.XConnect.Contact existingContact = client.Get(new IdentifiedContactReference("hubspotFormUser", email), new Sitecore.XConnect.ContactExpandOptions(ScoreFacet.DefaultFacetKey, ScoreNameFacet.DefaultFacetKey, PersonalInformation.DefaultFacetKey, EmailAddressList.DefaultFacetKey));

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

                        return(null);
                    }
                    catch (XdbExecutionException)
                    {
                        return(null);
                    }
                }
            }
            catch (Exception ex)
            {
                Sitecore.Diagnostics.Log.Error("Error updating contact score facet with the email:" + email, ex, this);
                return(null);
            }
        }
        private static void SetEmail(Contact contact, IXDbContactWithEmail xDbContact, IXdbContext client)
        {
            if (string.IsNullOrEmpty(xDbContact.Email))
            {
                return;
            }
            var emailFacet = contact.Emails();

            if (emailFacet == null)
            {
                emailFacet = new EmailAddressList(new EmailAddress(xDbContact.Email, false), "Preferred");
            }
            else
            {
                if (emailFacet.PreferredEmail?.SmtpAddress == xDbContact.Email)
                {
                    return;
                }
                emailFacet.PreferredEmail = new EmailAddress(xDbContact.Email, false);
            }
            client.SetEmails(contact, emailFacet);
        }
Example #29
0
        public IWeKnowTree GetWhatWeKnowTreeFromXConnectContact(Sitecore.XConnect.Contact XConnectContact)
        {
            Sitecore.Diagnostics.Log.Debug(ProjConstants.Logger.Prefix + "s) GetWhatWeKnowTreeFromXConnectContact");

            IWeKnowTree toReturn = new Concretions.WhatWeKnowTree("What We Know", Options);

            using (XConnectClient xConnectClient = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
            {
                try
                {
                    var tier1Nodes = new Tier1Nodes(XConnectContact, Options);
                    toReturn.Root.AddNodes(tier1Nodes.Tier1NodeBuilder(null, xConnectClient, XConnectContact));
                }
                catch (XdbExecutionException ex)
                {
                    Sitecore.Diagnostics.Log.Error(ProjConstants.Logger.Prefix + ex.Message, this);
                }
            }

            Sitecore.Diagnostics.Log.Debug(ProjConstants.Logger.Prefix + "e) GetWhatWeKnowTreeFromXConnectContact");
            return(toReturn);
        }
 public bool SaveFacet <T>(Sitecore.XConnect.Contact contact, string FacetKey, T Facet) where T : Facet
 {
     using (XConnectClient client = SitecoreXConnectClientConfiguration.GetClient())
     {
         try
         {
             client.SetFacet(contact, FacetKey, Facet);
             client.Submit();
             return(true);
         }
         catch (XdbExecutionException ex)
         {
             Log.Error($"XConnectContactRepository: Error saving contact data to xConnect. Facet: '{Facet}' Contact: '{contact.Id}'", ex, this);
             return(false);
         }
         catch (Exception ex)
         {
             Log.Error("XConnectContactRepository: Error communication with the xConnect colllection service", ex, this);
             return(false);
         }
     }
 }