Last active
May 10, 2019 00:09
-
-
Save markgibbons25/5432ca842cf5a55db9190c869723522e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Newtonsoft.Json; | |
using Sitecore.Analytics; | |
using Sitecore.Analytics.Model; | |
using Sitecore.Analytics.Tracking; | |
using Sitecore.Diagnostics; | |
using Sitecore.XConnect; | |
using Sitecore.XConnect.Client; | |
using Sitecore.XConnect.Client.Configuration; | |
using Sitecore.XConnect.Collection.Model; | |
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
namespace Yours | |
{ | |
public class ContactRepository : IContactRepository | |
{ | |
private readonly ContactManager _contactmanager; | |
public ContactRepository() | |
{ | |
_contactmanager = Sitecore.Configuration.Factory.CreateObject("tracking/contactManager", true) as ContactManager; | |
} | |
public bool SaveContactData(ContactModel contactModel) | |
{ | |
try | |
{ | |
var contactReference = GetIdentifiedContactReference(); | |
using (var client = SitecoreXConnectClientConfiguration.GetClient()) | |
{ | |
var contact = client.Get(contactReference, new ContactExpandOptions(PersonalInformation.DefaultFacetKey)); | |
// Update your contact facets | |
client.Submit(); | |
ReloadContact(); | |
} | |
return true; | |
} | |
catch (Exception ex) | |
{ | |
Log.Error("Error saving data to profile", ex, this); | |
return false; | |
} | |
} | |
private IdentifiedContactReference GetIdentifiedContactReference() | |
{ | |
if (Tracker.Enabled && !Tracker.Current.IsActive) | |
{ | |
Tracker.StartTracking(); | |
} | |
if (Tracker.Current?.Contact == null) | |
{ | |
Log.Warn("Tracker.Current?.Contact == null", this); | |
return null; | |
} | |
if (Tracker.Current.Contact.IsNew) | |
{ | |
Tracker.Current.Contact.ContactSaveMode = ContactSaveMode.AlwaysSave; | |
_contactmanager.SaveContactToCollectionDb(Tracker.Current.Contact); | |
} | |
var id = Tracker.Current.Contact.Identifiers.FirstOrDefault(); | |
return Tracker.Current.Contact.IsNew || Tracker.Current.Contact.Identifiers.Count == 0 | |
? new IdentifiedContactReference(Sitecore.Analytics.XConnect.DataAccess.Constants.IdentifierSource, Tracker.Current.Contact.ContactId.ToString("N")) | |
: new IdentifiedContactReference(id.Source, id.Identifier); | |
} | |
private void ReloadContact() | |
{ | |
if (Tracker.Current?.Session == null) | |
{ | |
Log.Warn("Tracker.Current?.Contact == null", this); | |
return; | |
} | |
_contactmanager.RemoveFromSession(Tracker.Current.Contact.ContactId); | |
Tracker.Current.Session.Contact = _contactmanager.LoadContact(Tracker.Current.Contact.ContactId); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment