xConnect tutorial #3: Get contacts

You need to complete xConnect tutorial #1 and xConnect tutorial #2 before starting this tutorial. This tutorial relies on the sample contact and interaction data created in the preceding tutorials.

  1. Execute the code from Tutorial #2 to create a new contact - take note of the identifier that is used to create the contact. For example: myrtlesitecore9d1f652848f247219be9e1dbea4dd346.

  2. Modify your code as shown in the "// Get a known contact" section, or create a new console application - use the known identifier to retrieve a contact that was created previously. Be aware of the following:

    • External systems should not store contact IDs, therefore it is unlikely that you will use the .Get<Contact> overload that accepts a contact ID.

    • To retrieve a facet, you must explicitly request it as part of the ContactExpandOptions as shown in the example.

    using Sitecore.XConnect;
    using Sitecore.XConnect.Client;
    using Sitecore.XConnect.Client.WebApi;
    using Sitecore.XConnect.Collection.Model;
    using Sitecore.XConnect.Schema;
    using Sitecore.Xdb.Common.Web;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Sitecore.Xdb.Common.Web;
    
    namespace Sitecore.Documentation
    {
        public class Program
        {
            private static void Main(string[] args)
            {
                MainAsync(args).ConfigureAwait(false).GetAwaiter().GetResult();
                Console.ForegroundColor = ConsoleColor.DarkGreen;
                Console.WriteLine("");
                Console.WriteLine("END OF PROGRAM.");
                Console.ReadKey();
            }
    
            private static async Task MainAsync(string[] args)
            {
                Console.WriteLine(" ");
    
                CertificateWebRequestHandlerModifierOptions options =
                CertificateWebRequestHandlerModifierOptions.Parse("StoreName=My;StoreLocation=LocalMachine;FindType=FindByThumbprint;FindValue=15E6693B0AECB63DE57D991EC363CA462DC52432");
    
                var certificateModifier = new CertificateWebRequestHandlerModifier(options);
    
                List<IHttpClientModifier> clientModifiers = new List<IHttpClientModifier>();
                var timeoutClientModifier = new TimeoutHttpClientModifier(new TimeSpan(0, 0, 20));
                clientModifiers.Add(timeoutClientModifier);
    
                var collectionClient = new CollectionWebApiClient(new Uri("https://xconnect/odata"), clientModifiers, new[] { certificateModifier });
                var searchClient = new SearchWebApiClient(new Uri("https://xconnect/odata"), clientModifiers, new[] { certificateModifier });
                var configurationClient = new ConfigurationWebApiClient(new Uri("https://xconnect/configuration"), clientModifiers, new[] { certificateModifier });
    
                var cfg = new XConnectClientConfiguration(
                    new XdbRuntimeModel(CollectionModel.Model), collectionClient, searchClient, configurationClient);
    
                try
                {
                    cfg.Initialize(); // cfg.InitializeAsync();
    
                    // Print xConnect if configuration is valid
                    var arr = new[]
                    {
                                @"            ______                                                       __     ",
                                @"           /      \                                                     |  \    ",
                                @" __    __ |  $$$$$$\  ______   _______   _______    ______    _______  _| $$_   ",
                                @"|  \  /  \| $$   \$$ /      \ |       \ |       \  /      \  /       \|   $$ \  ",
                                @"\$$\/  $$| $$      |  $$$$$$\| $$$$$$$\| $$$$$$$\|  $$$$$$\|  $$$$$$$ \$$$$$$   ",
                                @" >$$  $$ | $$   __ | $$  | $$| $$  | $$| $$  | $$| $$    $$| $$        | $$ __  ",
                                @" /  $$$$\ | $$__/  \| $$__/ $$| $$  | $$| $$  | $$| $$$$$$$$| $$_____   | $$|  \",
                                @"|  $$ \$$\ \$$    $$ \$$    $$| $$  | $$| $$  | $$ \$$     \ \$$     \   \$$  $$",
                                @" \$$   \$$  \$$$$$$   \$$$$$$  \$$   \$$ \$$   \$$  \$$$$$$$  \$$$$$$$    \$$$$ "
                            };
                    Console.WindowWidth = 160;
                    foreach (string line in arr)
                        Console.WriteLine(line);
    
                }
                catch (XdbModelConflictException ce)
                {
                    Console.WriteLine("ERROR:" + ce.Message);
                    return;
                }
    
                // Initialize a client using the validated configuration
                using (var client = new XConnectClient(cfg))
                {
                    try
                    {
                        // Get a known contact
                        IdentifiedContactReference reference = new IdentifiedContactReference("twitter", "myrtlesitecore9d1f652848f247219be9e1dbea4dd346");
    
                        Contact existingContact = await client.GetAsync<Contact>(reference, new ContactExpandOptions(new string[] { PersonalInformation.DefaultFacetKey }));
    
                        PersonalInformation existingContactFacet = existingContact.GetFacet<PersonalInformation>(PersonalInformation.DefaultFacetKey);
    
                        Console.WriteLine("Contact ID: " + existingContact.Id.ToString());
                        Console.WriteLine("Contact Name: " + existingContactFacet.FirstName);
    
                        Console.ReadLine();
                    }
                    catch (XdbExecutionException ex)
                    {
                        // Deal with exception
                    }
                }
            }
        }
    }
    
  3. Press F5 to run the console - you should get a single contact and the associated PersonalInformation facet. Try to run this code without any expand options - the facet will be null and you will get an exception when you try to use it.

  4. To retrieve a contact’s interactions, you must set the Interactions property of ContactExpandOptions as shown in the following example. Be aware of the following:

    • To retrieve all interactions, set the StartDateTime and EndDateTime as shown - interactions between these two dates are returned.

    • You can also specify a Limit if you only want the top X number of interactions.

    • Notice that you must specify which interaction facets to return.

    using Sitecore.XConnect;
    using Sitecore.XConnect.Client;
    using Sitecore.XConnect.Client.WebApi;
    using Sitecore.XConnect.Collection.Model;
    using Sitecore.XConnect.Schema;
    using Sitecore.Xdb.Common.Web;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Sitecore.Xdb.Common.Web;
    
    namespace Sitecore.Documentation
    {
        public class Program
        {
            private static void Main(string[] args)
            {
                MainAsync(args).ConfigureAwait(false).GetAwaiter().GetResult();
                Console.ForegroundColor = ConsoleColor.DarkGreen;
                Console.WriteLine("");
                Console.WriteLine("END OF PROGRAM.");
                Console.ReadKey();
            }
    
            private static async Task MainAsync(string[] args)
            {
                Console.WriteLine(" ");
    
                CertificateWebRequestHandlerModifierOptions options =
                CertificateWebRequestHandlerModifierOptions.Parse("StoreName=My;StoreLocation=LocalMachine;FindType=FindByThumbprint;FindValue=15E6693B0AECB63DE57D991EC363CA462DC52432");
    
                var certificateModifier = new CertificateWebRequestHandlerModifier(options);
    
                List<IHttpClientModifier> clientModifiers = new List<IHttpClientModifier>();
                var timeoutClientModifier = new TimeoutHttpClientModifier(new TimeSpan(0, 0, 20));
                clientModifiers.Add(timeoutClientModifier);
    
                var collectionClient = new CollectionWebApiClient(new Uri("https://xconnect/odata"), clientModifiers, new[] { certificateModifier });
                var searchClient = new SearchWebApiClient(new Uri("https://xconnect/odata"), clientModifiers, new[] { certificateModifier });
                var configurationClient = new ConfigurationWebApiClient(new Uri("https://xconnect/configuration"), clientModifiers, new[] { certificateModifier });
    
                var cfg = new XConnectClientConfiguration(
                    new XdbRuntimeModel(CollectionModel.Model), collectionClient, searchClient, configurationClient);
    
                try
                {
                    cfg.Initialize(); // cfg.InitializeAsync();
    
                    // Print xConnect if configuration is valid
                    var arr = new[]
                    {
                                @"            ______                                                       __     ",
                                @"           /      \                                                     |  \    ",
                                @" __    __ |  $$$$$$\  ______   _______   _______    ______    _______  _| $$_   ",
                                @"|  \  /  \| $$   \$$ /      \ |       \ |       \  /      \  /       \|   $$ \  ",
                                @"\$$\/  $$| $$      |  $$$$$$\| $$$$$$$\| $$$$$$$\|  $$$$$$\|  $$$$$$$ \$$$$$$   ",
                                @" >$$  $$ | $$   __ | $$  | $$| $$  | $$| $$  | $$| $$    $$| $$        | $$ __  ",
                                @" /  $$$$\ | $$__/  \| $$__/ $$| $$  | $$| $$  | $$| $$$$$$$$| $$_____   | $$|  \",
                                @"|  $$ \$$\ \$$    $$ \$$    $$| $$  | $$| $$  | $$ \$$     \ \$$     \   \$$  $$",
                                @" \$$   \$$  \$$$$$$   \$$$$$$  \$$   \$$ \$$   \$$  \$$$$$$$  \$$$$$$$    \$$$$ "
                            };
                    Console.WindowWidth = 160;
                    foreach (string line in arr)
                        Console.WriteLine(line);
    
                }
                catch (XdbModelConflictException ce)
                {
                    Console.WriteLine("ERROR:" + ce.Message);
                    return;
                }
    
                // Initialize a client using the validated configuration
                using (var client = new XConnectClient(cfg))
                {
                    try
                    {
                        // Get a known contact
                        IdentifiedContactReference reference = new IdentifiedContactReference("twitter", "myrtlesitecoreb8858ce2a3bc4859a6b9ee25d50dcc67");
    
                        Contact existingContact = await client.GetAsync<Contact>(reference, new ContactExpandOptions(new string[] { PersonalInformation.DefaultFacetKey })
                        {
                            Interactions = new RelatedInteractionsExpandOptions(IpInfo.DefaultFacetKey)
                            {
                                StartDateTime = DateTime.MinValue,
                                EndDateTime = DateTime.MaxValue
                            }
                        });
    
                        if (existingContact != null)
                        {
                            PersonalInformation existingContactFacet = existingContact.GetFacet<PersonalInformation>(PersonalInformation.DefaultFacetKey);
    
                            Console.WriteLine("Contact ID: " + existingContact.Id.ToString());
                            Console.WriteLine("Contact Name: " + existingContactFacet.FirstName);
    
                            var interactions = existingContact.Interactions;
    
                            var i = 0;
    
                            Console.WriteLine("Interaction count: " + interactions.Count);
                            Console.WriteLine("");
    
                            // Cycle through all interactions
                            foreach (var interaction in interactions)
                            {
                                i++;
                                var ipInfo = interaction.GetFacet<IpInfo>(IpInfo.DefaultFacetKey);
                                Console.WriteLine("Interaction #" + i);
    
                                if (ipInfo != null)
                                {
                                    // For each interaction, print out the business name
                                    // associated with that interaction's IpInfo
                                    Console.WriteLine("Interaction business name: " + ipInfo.BusinessName);
                                }
                            }
    
                            Console.ReadLine();
                        }
    
                        Console.ReadLine();
                    }
                    catch (XdbExecutionException ex)
                    {
                        // Deal with exception
                    }
                }
            }
        }
    }
    
  5. Press F5 to run the console - in addition to a single contact and contact facet, you should now get that contact’s interaction and be able to read the IpInfo facet of those interactions:

    console-works-61.png

Getting interactions

To retrieve an interaction, you need the contact ID and the interaction ID. You can also pass in InteractionExpandOptions that will retrieve the related contact and any contact facets you specify:

var contactId = Guid.NewGuid();
var interactionId = Guid.NewGuid();

InteractionReference interactionReference = new InteractionReference(contactId, interactionId);

Interaction interaction = client.Get<Interaction>(interactionReference, new InteractionExpandOptions(new string[] { IpInfo.DefaultFacetKey })
{
    Contact = new RelatedContactExpandOptions(new string[] { PersonalInformation.DefaultFacetKey })
});