Walkthrough: Getting contacts

Current version: 9.0

This walkthrough is part three of the Extending the xConnect collection model walkthrough series. To complete this walkthrough, you must first complete walkthroughs part one and two.

This walkthrough describes how to:

  • Get a contact from a contact identifier

  • Get a contact's interactions

  • Get an interaction

Get a contact from a contact identifier

To get a contact from a contact identifier:

  1. In Visual Studio, in Solution Explorer, double-click the Program.cs file and replace the content with the following code:

    RequestResponse
    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.Threading.Tasks;
    
    namespace Sitecore.Documentation
    {
        public class Program
        {
            // From <xConnect instance>\App_Config\AppSettings.config
            const string CERTIFICATE_OPTIONS = 
                "StoreName=My;StoreLocation=LocalMachine;FindType=FindByThumbprint;FindValue=???";
    
            // From your installation
            const string XCONNECT_URL = "https://???XConnect.local";
    
            // From previous xConnect walkthrough
            const string CONTACT_IDENTIFIER = "myrtlesitecore???";
    
            private static void Main(string[] args)
            {
                MainAsync(args).ConfigureAwait(false).GetAwaiter().GetResult();
                System.Console.ForegroundColor = ConsoleColor.DarkGreen;
                System.Console.WriteLine("");
                Console.WriteLine("END OF PROGRAM.");
                Console.ReadKey();
            }
    
            private static async Task MainAsync(string[] args)
            {
                CertificateWebRequestHandlerModifierOptions options = CertificateWebRequestHandlerModifierOptions.Parse(CERTIFICATE_OPTIONS);
    
                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(XCONNECT_URL + "/odata"),
                    clientModifiers,
                    new[] { certificateModifier }
                );
    
                var searchClient = new SearchWebApiClient(
                    new Uri(XCONNECT_URL + "/odata"),
                    clientModifiers,
                    new[] { certificateModifier }
                );
    
                var configurationClient = new ConfigurationWebApiClient(
                    new Uri(XCONNECT_URL + "/configuration"),
                    clientModifiers,
                    new[] { certificateModifier }
                );
    
                var cfg = new XConnectClientConfiguration(
                    new XdbRuntimeModel(CollectionModel.Model),
                    collectionClient,
                    searchClient,
                    configurationClient
                );
    
                try
                {
                    cfg.Initialize();
    
                    // 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",
                            CONTACT_IDENTIFIER
                        );
    
                        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
                    }
                }
            }
        }
    }
  2. Edit the CERTIFICATE_THUMBPRINT, XCONNECT_URL, and CONTACT IDENTIFIER constants.

  3. Save the Program.cs file.

  4. Press F5 to run the app. If the connection is established, the app writes the following in the terminal:

    • The contact ID.

    • The contact name.

    A terminal with the contact details in the app output.
Important

To retrieve a facet, you must explicitly request it as part of ContactExpandOptions. If you run the code without ContactExpandOptions the facet becomes NULL, and you get an exception error when you try to use it.

Note

External systems are not normally used for storing contact IDs, so it is unlikely that you will use the .Get<Contact> overload that accepts a contact ID.

Get a contact's interactions

To get a contact's interactions, you must set the Interactions property of ContactExpandOptions.

To get a contact's interactions:

  1. In Visual Studio, in Solution Explorer, double-click the Program.cs file and replace the content with the following code:

    RequestResponse
    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.Threading.Tasks;
    
    namespace Sitecore.Documentation
    {
        public class Program
        {
            // From <xConnect instance>\App_Config\AppSettings.config
            const string CERTIFICATE_OPTIONS = 
                "StoreName=My;StoreLocation=LocalMachine;FindType=FindByThumbprint;FindValue=???";
    
            // From your installation
            const string XCONNECT_URL = "https://???XConnect.local";
    
            // From the previous xConnect walkthrough
            const string CONTACT_IDENTIFIER = "myrtlesitecore???";
    
            private static void Main(string[] args)
            {
                MainAsync(args).ConfigureAwait(false).GetAwaiter().GetResult();
                System.Console.ForegroundColor = ConsoleColor.DarkGreen;
                System.Console.WriteLine("");
                Console.WriteLine("END OF PROGRAM.");
                Console.ReadKey();
            }
    
            private static async Task MainAsync(string[] args)
            {
                CertificateWebRequestHandlerModifierOptions options = CertificateWebRequestHandlerModifierOptions.Parse(CERTIFICATE_OPTIONS);
    
                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(XCONNECT_URL + "/odata"),
                    clientModifiers,
                    new[] { certificateModifier }
                );
    
                var searchClient = new SearchWebApiClient(
                    new Uri(XCONNECT_URL + "/odata"),
                    clientModifiers,
                    new[] { certificateModifier }
                );
    
                var configurationClient = new ConfigurationWebApiClient(
                    new Uri(XCONNECT_URL + "/configuration"),
                    clientModifiers,
                    new[] { certificateModifier }
                );
    
                var cfg = new XConnectClientConfiguration(
                    new XdbRuntimeModel(CollectionModel.Model),
                    collectionClient,
                    searchClient,
                    configurationClient
                );
    
                try
                {
                    cfg.Initialize();
    
                    // 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",
                            CONTACT_IDENTIFIER
                        );
    
                        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
                    }
                }
            }
        }
    }
  2. Edit the CERTIFICATE_THUMBPRINT, XCONNECT_URL, and CONTACT IDENTIFIER constants.

  3. Save the Program.cs file.

  4. Press F5 to run the app. If the connection is established, the app writes the following in the terminal:

    • The contact ID.

    • The contact name.

    • The number of interactions.

    • The business name of each interaction.

    A terminal with the contact and interaction details in the app output.
Tip
  • You can adjust the StartDateTime and EndDateTime properties to retrieve only interactions between these two points in time.

  • You can set the Limit property to the number of interactions you want to see (counting from the first interaction).

Get an interaction

To get an interaction, you must have the contact ID and the interaction ID. You can also pass InteractionExpandOptions that gets the related contact and any contact facets you specify.

To get an interaction, use the following code:

RequestResponse
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
        })
    }
);

Go to the next walkthrough to learn how to search contacts and interactions.

Do you have some feedback for us?

If you have suggestions for improving this article,