---
title: "Walkthrough: Getting contacts"
slug: "walkthrough--getting-contacts"
abstract: "How to get a contact and its interactions from Sitecore xConnect."
---
# Walkthrough: Getting contacts

This walkthrough is part three of the [Extending the xConnect collection model walkthrough series](https://doc.sitecore.com/xp/en/developers/93/sitecore-experience-platform/extending-the-xconnect-collection-model-walkthrough-series.html "Extending the xConnect collection model walkthrough series"). To complete this walkthrough, you must first complete walkthroughs part [one](https://doc.sitecore.com/xp/en/developers/93/sitecore-experience-platform/walkthrough--creating-a-contact-and-an-interaction.html "Walkthrough: Creating a contact and an interaction") and [two](https://doc.sitecore.com/xp/en/developers/93/sitecore-experience-platform/walkthrough--setting-contact-and-interaction-facets.html "Walkthrough: Setting contact and interaction facets").

The walkthrough describes how to:

- Get a contact from a contact identifier
- Get a contact's interactions
- Get an interaction

> [!note]
> In Sitecore 9.1.0, in the `Sitecore.Xdb.Common.Web` namespace:
>
> -   `Certificate**WebRequest**HandlerModifierOptions` became `Certificate**HttpClient**HandlerModifierOptions`.
>
> -   `Certificate**WebRequest**HandlerModifier` became `Certificate**HttpClient**HandlerModifier`.

## 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:

    ```csharp
    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)
            {
                CertificateHttpClientHandlerModifierOptions options = CertificateHttpClientHandlerModifierOptions.Parse(CERTIFICATE_OPTIONS);

                var certificateModifier = new CertificateHttpClientHandlerModifier(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.](https://doc.sitecore.com/api/markdown-image/xp/en/developers/93/sitecore-experience-platform/images/xconn-tut3-code1.png)

> [!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:

    ```csharp
    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)
            {
                CertificateHttpClientHandlerModifierOptions options = CertificateHttpClientHandlerModifierOptions.Parse(CERTIFICATE_OPTIONS);

                var certificateModifier = new CertificateHttpClientHandlerModifier(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.](https://doc.sitecore.com/api/markdown-image/xp/en/developers/93/sitecore-experience-platform/images/xconn-tut3-code2.png)

> [!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:

```csharp
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](https://doc.sitecore.com/xp/en/developers/93/sitecore-experience-platform/walkthrough--searching-contacts-and-interactions.html "Walkthrough: Searching contacts and interactions").