Notes with code from Hishaamn Namooya blog post:
The TagProfile method retrieves the different profile presets (Profile Cards) and then update the tracking field of content item accordingly with the Profile Keys:
public void TagProfile(Item contentItem, Guid profileId)
{
// retrieve tracking information
ProfileUtil.GetProfiles(contentItem, out TrackingField trackingField);
var trackingValue = contentItem.Fields["__Tracking"].Value;
// get needed profile
var profile = trackingField.Profiles.FirstOrDefault(p => p.ProfileID.Guid.Equals(profileId));
if (profile != null)
{
var profileItem = new ProfileItem(profile.GetProfileItem());
var dictionary = new Dictionary<string, double>();
// TODO: implement logic that you need here
// iterate through profile cards and add NEEDED key/values to presets dictionary
foreach (var card in profileItem.ProfileCards)
{
dictionary.Add(card.InnerItem.Key, 10);
}
profile.SaveToField = true;
profile.Presets = dictionary;
SetProfileKeys(profile, profileItem);
TrackingField.UpdateKeyValues(profile);
}
// update "Tracking" field raw-value of contentItem
XDocument document = string.IsNullOrEmpty(trackingValue) ? new XDocument(new XElement("tracking")) : XDocument.Parse(trackingValue);
XElement xelement1 = document.Element("tracking");
if (xelement1 == null)
{
xelement1 = new XElement("tracking");
document.Add(xelement1);
}
List<XElement> list = xelement1.Elements("profile").ToList();
foreach (XElement t in list)
{
t.Remove();
}
foreach (XElement xelement2 in trackingField.Profiles.Where(x => x.SaveToField).Select(x => x.ToXElement()))
xelement1.Add(xelement2);
// save
using (new SecurityDisabler())
{
contentItem.Editing.BeginEdit();
contentItem.Fields["__Tracking"].Value = document.ToString();
contentItem.Editing.EndEdit();
}
}
The SetProfileKeys method is used to set the different profile keys:
public void SetProfileKeys(ContentProfile profile, ProfileItem profileItem)
{
foreach (ProfileKeyItem profileKeyItem in profileItem.Keys.ToList())
{
ProfileKeyItem keyItem = profileKeyItem;
if (profile.Keys.FirstOrDefault(k => string.Compare(k.Key, keyItem.Name, StringComparison.InvariantCultureIgnoreCase) == 0) == null)
{
ContentProfileKeyData key = new ContentProfileKeyData(keyItem)
{
Value = keyItem.GetDefaultValue()
};
profile.AddKey(key);
}
}
foreach (ContentProfileKeyData key in profile.Keys.Where(key => key.ProfileDefinitionId == Guid.Empty))
{
profile.RemoveKey(key);
}
TrackingField.UpdateKeyValues(profile);
}