Using xConnect Client in Non-Sitecore Context


Starting with Sitecore version 9, developers can interact with the Sitecore Experience Database (xDB) using xConnect. xConnect is a OData based service layer that allows communication with xDB data. Any trusted client can leverage xConnect Client API which exposes rich capabilities to search, read, and write contacts and interactions data. In this blog, I want to look at the details on how to instantiate xConnect Client in a non-Sitecore context. One of the reasons you would want to do this is if you need to extract xDB data into another system or application.

Prerequisites


To get started, we need to install a couple of NuGet packages. Here please select the version that corresponds to your Sitecore installed version. In my case, I’m working with Sitecore Experience Platform 9.0 rev. 180604 (9.0 Update-2), so I will install 9.0.180604 version of the packages.

PM> Install-Package Sitecore.XConnect.Client -Version 9.0.180604
PM> Install-Package Sitecore.XConnect.Collection.Model -Version 9.0.180604

We also need to locate the correct certificate thumbprint in order to establish the trusted connection with xConnect service. You can find that value in {xConnect_Install_Directory}\App_Config\AppSettings.config file.

xConnect AppSettings.config


xConnect Client


Let’s start by referencing the xConnect URL and info about the certificate. For the sake of brevity, I’m hardcoding those values but best practice is to retrieve those from a config file.

private readonly static string _xConnectUrl = "https://sc9.xconnect/";
private readonly static string _xConnectCertificate = 
    "StoreName=My;StoreLocation=LocalMachine;FindType=FindByThumbprint;FindValue=THUMBPRINT_VALUE";

Now we need to create an instance of XConnectClientConfiguration, which will contain the configurations for the client certificate, xConnect endpoints and xDB model.

var certificateOptions = CertificateWebRequestHandlerModifierOptions.Parse(_xConnectCertificate);
var certificateModifier = new CertificateWebRequestHandlerModifier(certificateOptions);

var clientModifiers = new List<IHttpClientModifier>();
var timeoutClientModifier = new TimeoutHttpClientModifier(new TimeSpan(0, 0, 30));
clientModifiers.Add(timeoutClientModifier);

var xConnectConfigurationClient = new ConfigurationWebApiClient(
                            new Uri(_xConnectUrl + "configuration"), 
                            clientModifiers, 
                            new[] { certificateModifier });

var xConnectCollectionClient = new CollectionWebApiClient(
                            new Uri(_xConnectUrl + "odata"), 
                            clientModifiers, 
                            new[] { certificateModifier });

var xConnectSearchClient = new SearchWebApiClient(
                            new Uri(_xConnectUrl + "odata"), 
                            clientModifiers, 
                            new[] { certificateModifier });

var xConnectClientConfig = new XConnectClientConfiguration(
                            new XdbRuntimeModel(CollectionModel.Model), 
                            xConnectCollectionClient, 
                            xConnectSearchClient, 
                            xConnectConfigurationClient);

try
{
    await xConnectClientConfig.InitializeAsync();
}
catch (XdbModelConflictException ex)
{
    // Handle exception
}

The next step is simply to instantiate new XConnectClient by passing XConnectClientConfiguration object to it.

var xConnectClient = new XConnectClient(xConnectClientConfig);

At this point we can create a sample query to retrieve some interactions. This will filter the interactions data to retrieve records with the specific event type and the start datetime.

try
{
    var query = xConnectClient.Interactions
                .Where(i => i.Events.OfType<PageViewEvent>().Any())
                .Where(i => i.StartDateTime > new DateTime(2019, 9, 1, 12, 0, 0)
                                                          .ToUniversalTime());

    var batchEnumerator = await query.GetBatchEnumerator(20);

    while (await batchEnumerator.MoveNext())
    {
        var batch = batchEnumerator.Current;

        // Do something with the data
    }
}
catch (XdbExecutionException ex)
{
    // Handle exception
}

 

Conclusion


I hope this example gives you a good starting point for exploring the Sitecore xConnect Client API, especially for the use cases when the xDB data needs to be exported into a third-party system. For more information about xConnect Client API please refer to Sitecore developer docs.

 

Tags: Sitecore, xConnect, xDB;

SEARCH ARTICLES