Created
November 24, 2024 13:48
-
-
Save eduvto/ca9f15ce01210c731a7b6b2db8312389 to your computer and use it in GitHub Desktop.
Sitecore Identify Contact
This file contains hidden or 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
<%@ Page Language="C#" %> | |
<%@ Import Namespace="System" %> | |
<%@ Import Namespace="System.Linq" %> | |
<%@ Import Namespace="Sitecore.Analytics" %> | |
<%@ Import Namespace="Sitecore.Analytics.Model" %> | |
<%@ Import Namespace="Sitecore.Configuration" %> | |
<%@ Import Namespace="Sitecore.XConnect" %> | |
<%@ Import Namespace="Sitecore.XConnect.Client" %> | |
<%@ Import Namespace="Sitecore.XConnect.Operations" %> | |
<%@ Import Namespace="Sitecore.XConnect.Collection.Model" %> | |
<%@ Import Namespace="Sitecore.Security.Authentication" %> | |
<%@ Import Namespace="Microsoft.Extensions.DependencyInjection" %> | |
<% | |
var results = new StringBuilder(); | |
// Parameters | |
string userName = Request.Form["userName"]; | |
string source = Request.Form["source"]; | |
string firstName = Request.Form["firstName"]; | |
string lastName = Request.Form["lastName"]; | |
DateTime? birthdate = DateTime.TryParse(Request.Form["birthdate"], out DateTime parsedDateTime) ? parsedDateTime : (DateTime?)null; | |
string middleName = Request.Form["middleName"]; | |
string gender = Request.Form["gender"]; | |
string jobTitle = Request.Form["jobTitle"]; | |
string nickname = Request.Form["nickname"]; | |
string suffix = Request.Form["suffix"]; | |
string title = Request.Form["title"]; | |
string preferredLanguage = Request.Form["preferredLanguage"]; | |
string email = Request.Form["email"]; | |
string country = Request.Form["country"]; | |
Contact contact = null; | |
if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(source)) | |
{ | |
// Start up time watcher | |
var watch = new System.Diagnostics.Stopwatch(); | |
watch.Start(); | |
// CreateAndLoginSitecoreVirtualUser | |
try | |
{ | |
Sitecore.Diagnostics.Log.Info("CreateAndLoginSitecoreVirtualUser begin", this); | |
var virtualUser = AuthenticationManager.BuildVirtualUser(Sitecore.Context.Site.Properties["domain"]+"\\"+userName, true); | |
Sitecore.Security.UserProfile profile = virtualUser.Profile; | |
profile.Name = firstName; | |
profile.Email = email; | |
profile.Save(); | |
AuthenticationManager.LoginVirtualUser(virtualUser); | |
Sitecore.Diagnostics.Log.Info("CreateAndLoginSitecoreVirtualUser success. username "+virtualUser.Name, this); | |
} | |
catch (Exception ex) | |
{ | |
Sitecore.Diagnostics.Log.Error("Error in CreateAndLoginSitecoreVirtualUser. ", ex, this); | |
} | |
// IdentifyAs | |
var isTrackingActive = Tracker.Enabled && (Tracker.Current != null) && Tracker.Current.IsActive; | |
if (isTrackingActive) | |
{ | |
// Identify | |
bool identified; | |
try | |
{ | |
//Tracker.Current.Session.IdentifyAs(source, userName); | |
//identified = true; | |
var identificationManager = Sitecore.DependencyInjection.ServiceLocator.ServiceProvider.GetRequiredService<Sitecore.Analytics.Tracking.Identification.IContactIdentificationManager>(); | |
var result = identificationManager.IdentifyAs(new Sitecore.Analytics.Tracking.Identification.KnownContactIdentifier(source, userName)); | |
if(!result.Success) | |
throw new Exception($"{result.ErrorCode} - {result.ErrorMessage}."); | |
else | |
identified = true; | |
} | |
catch (Exception ex) | |
{ | |
results.AppendLine("Error identifying contact: "+ex.Message+" - StackTrace: "+ex.StackTrace); | |
identified = false; | |
} | |
// Get contact with facets to show its info | |
if (identified) | |
{ | |
var contactExpandOptions = new Sitecore.XConnect.ContactExpandOptions(PersonalInformation.DefaultFacetKey, EmailAddressList.DefaultFacetKey); | |
using (XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient()) | |
{ | |
try | |
{ | |
var reference = new IdentifiedContactReference(source, userName); | |
contact = client.Get<Contact>(reference, contactExpandOptions); | |
var doSubmit = false; | |
// PersonalInformation Section | |
var personalInformationFacet = contact.GetFacet<PersonalInformation>(PersonalInformation.DefaultFacetKey); | |
if (personalInformationFacet == null) | |
{ | |
var personalInformation = new PersonalInformation() | |
{ | |
FirstName = firstName, | |
LastName = lastName, | |
Birthdate = birthdate, | |
MiddleName = middleName, | |
Gender = gender, | |
JobTitle = jobTitle, | |
Nickname = nickname, | |
Suffix = suffix, | |
Title = title, | |
PreferredLanguage = preferredLanguage | |
}; | |
client.SetFacet(contact, PersonalInformation.DefaultFacetKey, personalInformation); | |
doSubmit = true; | |
} | |
else if (!string.Equals(personalInformationFacet.FirstName, firstName) || | |
!string.Equals(personalInformationFacet.LastName, lastName)|| | |
!DateTime.Equals(personalInformationFacet.Birthdate, birthdate)|| | |
!string.Equals(personalInformationFacet.MiddleName, middleName)|| | |
!string.Equals(personalInformationFacet.Gender, gender)|| | |
!string.Equals(personalInformationFacet.JobTitle, jobTitle)|| | |
!string.Equals(personalInformationFacet.Nickname, nickname)|| | |
!string.Equals(personalInformationFacet.Suffix, suffix)|| | |
!string.Equals(personalInformationFacet.Title, title)|| | |
!string.Equals(personalInformationFacet.PreferredLanguage, preferredLanguage)) | |
{ | |
personalInformationFacet.FirstName = firstName; | |
personalInformationFacet.LastName = lastName; | |
personalInformationFacet.Birthdate = birthdate; | |
personalInformationFacet.MiddleName = middleName; | |
personalInformationFacet.Gender = gender; | |
personalInformationFacet.JobTitle = jobTitle; | |
personalInformationFacet.Nickname = nickname; | |
personalInformationFacet.Suffix = suffix; | |
personalInformationFacet.Title = title; | |
personalInformationFacet.PreferredLanguage = preferredLanguage; | |
client.SetFacet(contact, PersonalInformation.DefaultFacetKey, personalInformationFacet); | |
doSubmit = true; | |
} | |
// EmailAddressList Section | |
var emailAddressListFacet = contact.GetFacet<EmailAddressList>(EmailAddressList.DefaultFacetKey); | |
if (emailAddressListFacet == null) | |
{ | |
var emails = new EmailAddressList(new EmailAddress(email, true), "Work"); | |
client.SetFacet(contact, EmailAddressList.DefaultFacetKey, emails); | |
doSubmit = true; | |
} | |
else if (!string.Equals(contact.Emails()?.PreferredEmail?.SmtpAddress, email)) | |
{ | |
emailAddressListFacet.PreferredEmail = new EmailAddress(email, true); | |
emailAddressListFacet.PreferredKey = "Work"; | |
client.SetFacet(contact, EmailAddressList.DefaultFacetKey, emailAddressListFacet); | |
doSubmit = true; | |
} | |
// User Location | |
var userLocationInfo = new WhoIsInformation() | |
{ | |
Country = country | |
}; | |
if (Tracker.Current.Interaction.GeoData.Country != userLocationInfo.Country) | |
{ | |
Sitecore.Analytics.Tracker.Current.Interaction.SetWhoIsInformation(userLocationInfo); | |
} | |
if (doSubmit) | |
{ | |
// Remove contact data from shared session state - contact will be re-loaded | |
// during subsequent request with updated facets | |
var manager = Factory.CreateObject("tracking/contactManager", true) as Sitecore.Analytics.Tracking.ContactManager; | |
if (manager != null) | |
{ | |
manager.RemoveFromSession(Tracker.Current.Contact.ContactId); | |
Tracker.Current.Session.Contact = manager.LoadContact(Tracker.Current.Contact.ContactId); | |
} | |
client.Submit(); | |
} | |
} | |
catch (XdbExecutionException ex) | |
{ | |
results.AppendLine("Error: "+ex.Message+" - StackTrace: "+ex.StackTrace); | |
} | |
} | |
} | |
} | |
else | |
results.AppendLine("Tracker is disabled"); | |
// Show contact details | |
if (contact == null) | |
results.AppendLine("Contact not found"); | |
else | |
{ | |
results.AppendLine("Contact ID: "+contact.Id.ToString()); | |
results.AppendLine(); | |
foreach (var identifier in contact.Identifiers) | |
results.AppendLine("Source: '"+identifier.Source+"' - Identifier: '"+identifier.Identifier+"'"); | |
var emailAddressList = contact.GetFacet<EmailAddressList>(); | |
// Get E-mail | |
email = "None"; | |
if (emailAddressList != null && emailAddressList.PreferredEmail != null && !string.IsNullOrEmpty(emailAddressList.PreferredEmail.SmtpAddress)) | |
email = emailAddressList.PreferredEmail.SmtpAddress; | |
// Anonymous | |
var anonymous = contact.IsKnown ? string.Empty : " (Anonymous)"; | |
results.AppendLine(); | |
results.AppendLine(anonymous); | |
} | |
watch.Stop(); | |
results.AppendLine(); | |
results.AppendLine("Execution Time: "+watch.ElapsedMilliseconds+" ms"); | |
} | |
%> | |
<!DOCTYPE html> | |
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"> | |
<head> | |
<meta charset="utf-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> | |
<!-- Bootstrap CSS --> | |
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> | |
<title>Identify Contact</title> | |
</head> | |
<body> | |
<h1>Identify Contact</h1> | |
<form method="post"> | |
<div class="container"> | |
<div class="row mb-3"> | |
<label for="source" class="col-sm-2 col-form-label">Identifier Source:</label> | |
<div class="col-sm-4"> | |
<input type="text" class="form-control" id="source" name="source" value="<%=source%>" required/> | |
</div> | |
<label for="userName" class="col-sm-2 col-form-label">Identifier value (username):</label> | |
<div class="col-sm-4"> | |
<input type="text" class="form-control" id="userName" name="userName" value="<%=userName%>" required/> | |
</div> | |
</div> | |
<div class="row mb-3"> | |
<label for="email" class="col-sm-2 col-form-label">Email:</label> | |
<div class="col-sm-4"> | |
<input type="email" class="form-control" id="email" name="email" value="<%=email%>" required/> | |
</div> | |
<label for="firstName" class="col-sm-2 col-form-label">First Name:</label> | |
<div class="col-sm-4"> | |
<input type="text" class="form-control" id="firstName" name="firstName" value="<%=firstName%>" required/> | |
</div> | |
</div> | |
<div class="row mb-3"> | |
<label for="middleName" class="col-sm-2 col-form-label">Middle Name:</label> | |
<div class="col-sm-4"> | |
<input type="text" class="form-control" id="middleName" name="middleName" value="<%=middleName%>" /> | |
</div> | |
<label for="lastName" class="col-sm-2 col-form-label">Last Name:</label> | |
<div class="col-sm-4"> | |
<input type="text" class="form-control" id="lastName" name="lastName" value="<%=lastName%>" /> | |
</div> | |
</div> | |
<div class="row mb-3"> | |
<label for="birthdate" class="col-sm-2 col-form-label">Birthdate:</label> | |
<div class="col-sm-4"> | |
<input type="date" class="form-control" id="birthdate" name="birthdate" value="<%=birthdate%>" /> | |
</div> | |
<label for="gender" class="col-sm-2 col-form-label">Gender:</label> | |
<div class="col-sm-4"> | |
<input type="text" class="form-control" id="gender" name="gender" value="<%=gender%>" /> | |
</div> | |
</div> | |
<div class="row mb-3"> | |
<label for="jobTitle" class="col-sm-2 col-form-label">Job Title:</label> | |
<div class="col-sm-4"> | |
<input type="text" class="form-control" id="jobTitle" name="jobTitle" value="<%=jobTitle%>" /> | |
</div> | |
<label for="nickname" class="col-sm-2 col-form-label">Nickname:</label> | |
<div class="col-sm-4"> | |
<input type="text" class="form-control" id="nickname" name="nickname" value="<%=nickname%>" /> | |
</div> | |
</div> | |
<div class="row mb-3"> | |
<label for="suffix" class="col-sm-2 col-form-label">Suffix:</label> | |
<div class="col-sm-4"> | |
<input type="text" class="form-control" id="suffix" name="suffix" value="<%=suffix%>" /> | |
</div> | |
<label for="title" class="col-sm-2 col-form-label">Title:</label> | |
<div class="col-sm-4"> | |
<input type="text" class="form-control" id="title" name="title" value="<%=title%>" /> | |
</div> | |
</div> | |
<div class="row mb-3"> | |
<label for="preferredLanguage" class="col-sm-2 col-form-label">Preferred Language:</label> | |
<div class="col-sm-4"> | |
<input type="text" class="form-control" id="preferredLanguage" name="preferredLanguage" value="<%=preferredLanguage%>" /> | |
</div> | |
</div> | |
<div class="row mb-3"> | |
<div class="col-sm-10 offset-sm-2"> | |
<button type="submit" class="btn btn-primary">Submit</button> | |
</div> | |
</div> | |
</div> | |
</form> | |
<% | |
// Show results | |
if (results.Length > 0) | |
{ | |
%> | |
<h2>Results</h2> | |
<pre><%=results.ToString()%></pre> | |
<% | |
} | |
%> | |
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Put this file into your Sitecore CD website file system and open it on web browser.