Using the Kentico Cloud Personalization API

   —   

Personalizing a user’s experience is a great way to make a connection with your audience. By customizing their visit to your site, you create a welcoming environment that helps build loyalty and trust. Along with great content management and delivery capabilities, Kentico Cloud also offers a dedicated API for implementing this tailored experience. In this article, I’ll show you how to integrate the Kentico Cloud Personalization API within your application.

Unlike traditional CMS’s, Kentico Cloud get updates bi-weekly. Because the platform is hosted in Azure and managed by the Kentico team, improvements and enhancements can be rolled out much quicker than traditional content management platforms. This means that there is a constant stream of new capabilities each month to incorporate into your solutions.

One of the newest aspects of Kentico Cloud is the Personalization API. This service allows you to customize the user experience by exposing behavior and preference data collected about your visitors. In this article, I want to show you how I used this API to create a unique experience for my site visitors.

Planning the integration

The first step of the process was to evaluate the service to see what it can do. After researching the API documentation and samples, I decided to leverage the “Current Location” capability within my site. For each site visitor, Kentico Cloud can approximate their location and return that information via the API. Using that information, I thought it might be cool to show how far the user is from different points of interests around the world. 

Adding the Points of Interest to Kentico Cloud

After figuring out what I wanted to do, I created my content type within Kentico Cloud. Here’s a screenshot of the new type.

Content Type

With these basic fields, I could easily populate my list of POIs to use within my application.

POI List

POI

Adding the Nuget Packages

After entering my content, I was ready to add the Personalization API Nuget Packages. In the Nuget Package Manager, I searched for KenticoCloud.Personalization. Because my site is a .NET Core MVC site, I selected the KenticoCloud.Personalization and KenticoCloud.Personalization.AspNetCore packages. Be sure to select the package that fits your project architecture.

Personalization Nuget Package

I then got my Personalization API Key from my Development tab for my Kentico Cloud project.

Personalization API Key

Because I would need to find the user’s latitude and longitude based on their location, I added the BingMapsRESTToolkit Nuget Package. Note that you will need to get a Bing API Key to use this service. You can find out more about that process here.

Bing Maps REST Toolkit Nuget Package

Lastly, I added the Personalization and Bing Maps API keys to my appsettings.json file.

appsettings.json

Using the API

With all the plumbing in place, I was ready to add my integration logic. I decided I wanted to display my “You are XXX miles from XXX” message on my About page, so I updated my AboutController with two Personalization functions to return the user id and session id.

// Get the user location information var uid = this.Request.GetCurrentPersonalizationUid(); var sid = this.Request.GetCurrentPersonalizationSid();

I then created a helper class to perform my distance calculation. I passed the uid and sid values, along with my API Keys to my new function.

await Helpers.PersonalizationHelper.GetVisitorDistance(Configuration.GetValue<string>("AppSettings:KenticoDeliveryProjectID"), uid, sid, Configuration.GetValue<string>("AppSettings:KenticoEngagePersonalizationAPIKey"), Configuration.GetValue<string>("AppSettings:BingMapsAPIKey"), ViewBag);

In my new class, I retrieved my list of POIs and selected a random location. With that location, I created a new Coordinate object (using the BingMapsRESTToolkit) to store the latitude and longitude of my POI.

// Get the POIs DeliveryClient client = new DeliveryClient(pid); var response = await client.GetItemsAsync( new EqualsFilter("system.type", "point_of_interest"), new ElementsParameter("latitude", "longitude") ); if (response != null) { Random rnd = new Random(); int x = rnd.Next(response.Items.Count); Coordinate coorPOI = new Coordinate(Convert.ToDouble(response.Items[x].GetString("latitude")), Convert.ToDouble(response.Items[x].GetString("longitude"))); … }

Next, I got the user’s location using the Personalization API.

// Get the user location information var engageclient = new PersonalizationClient(strPersonalizationAPIKey); var currentlocation = await engageclient.GetCurrentLocationAsync(uid, sid);

I then used the BingMapsRESTToolkit API to find the user’s latitude and longitude.

// Get the users lat/lon var r = ServiceManager.GetResponseAsync(new GeocodeRequest() { BingMapsKey = strBingMapsAPIKey, Address = new SimpleAddress() { Locality = currentlocation.City, AdminDistrict = currentlocation.State } }).GetAwaiter().GetResult();

After getting my results back form Bing, I created a new Coordinate object using the response.

Location loc = r.ResourceSets[0].Resources[0] as Location; Coordinate coorUser = new Coordinate(loc.Point.Coordinates[0], loc.Point.Coordinates[1]);

I then did some math (which I totally found online) to compare the POI’s lat/lon with the user’s lat/lon to determine the distance.

// Determine the user's distance from the POI double rlat1 = Math.PI * coorPOI.Latitude / 180; double rlat2 = Math.PI * coorUser.Latitude / 180; double theta = coorPOI.Longitude - coorUser.Longitude; double rtheta = Math.PI * theta / 180; double dist = Math.Sin(rlat1) * Math.Sin(rlat2) + Math.Cos(rlat1) * Math.Cos(rlat2) * Math.Cos(rtheta); dist = Math.Acos(dist); dist = dist * 180 / Math.PI; dist = dist * 60 * 1.1515;

With that, I populated my ViewBag object with the message, which I planned to show on the About page.

vb.DistanceMessage = "Did you know that you are about " + string.Format("{0:n0}", Math.Round(dist, 0)) + " miles from " + response.Items[x].System.Name + "?";

Testing

With all the code in place, I was ready to test. I published my changes to Azure and hit my About page. I confirmed that the site calculated my distance to a random POI.

Testing 1

I then cleared my cached and hit page again. This forced the site to choose a new POI and calculate that distance.

Testing 2

If you want to test out the functionality, head over to my About page here.

Moving Forward

Ensuring each user has a personalized experience on your site is key to building customer loyalty and satisfaction. Hopefully my example demonstrate how easily you can leverage your Personalization data within your applications. In my case, I can now show an interesting fact to every user, customized for their specific location. As the Kentico Cloud team continues to build out the API, you will be able access even more data and use it within your projects. Good luck!

If you want to know more about the Personalization API, click here.

Here is the full code of my Helper class, if you need it.

using BingMapsRESTToolkit; using KenticoCloud.Personalization; using System; using System.Threading.Tasks; using KenticoCloud.Delivery; namespace Soltisweb.Helpers { public class PersonalizationHelper { public static async Task GetVisitorDistance(string pid, string uid, string sid, string strPersonalizationAPIKey, string strBingMapsAPIKey, dynamic vb) { try { // Get the user location information var engageclient = new PersonalizationClient(strPersonalizationAPIKey); var currentlocation = await engageclient.GetCurrentLocationAsync(uid, sid); // Get the POIs DeliveryClient client = new DeliveryClient(pid); var response = await client.GetItemsAsync( new EqualsFilter("system.type", "point_of_interest"), new ElementsParameter("latitude", "longitude") ); if (response != null) { Random rnd = new Random(); int x = rnd.Next(response.Items.Count); Coordinate coorPOI = new Coordinate(Convert.ToDouble(response.Items[x].GetString("latitude")), Convert.ToDouble(response.Items[x].GetString("longitude"))); // Get the users lat/lon var r = ServiceManager.GetResponseAsync(new GeocodeRequest() { BingMapsKey = strBingMapsAPIKey, Address = new SimpleAddress() { Locality = currentlocation.City, AdminDistrict = currentlocation.State } }).GetAwaiter().GetResult(); if (r != null && r.ResourceSets != null && r.ResourceSets.Length > 0 && r.ResourceSets[0].Resources != null && r.ResourceSets[0].Resources.Length > 0) { Location loc = r.ResourceSets[0].Resources[0] as Location; Coordinate coorUser = new Coordinate(loc.Point.Coordinates[0], loc.Point.Coordinates[1]); // Determine the user's distance from the POI double rlat1 = Math.PI * coorPOI.Latitude / 180; double rlat2 = Math.PI * coorUser.Latitude / 180; double theta = coorPOI.Longitude - coorUser.Longitude; double rtheta = Math.PI * theta / 180; double dist = Math.Sin(rlat1) * Math.Sin(rlat2) + Math.Cos(rlat1) * Math.Cos(rlat2) * Math.Cos(rtheta); dist = Math.Acos(dist); dist = dist * 180 / Math.PI; dist = dist * 60 * 1.1515; vb.DistanceMessage = "Did you know that you are about " + string.Format("{0:n0}", Math.Round(dist, 0)) + " miles from " + response.Items[x].System.Name + "?"; } } } catch (Exception) { } } } }

This blog is intended for informational purposes only and provides an example of one of the many ways to accomplish the described task. Always consult Kentico Documentation for the best practices and additional examples that may be more effective in your specific situation.

Share this article on   LinkedIn Google+

Bryan Soltis

Hello. I am a Technical Evangelist here at Kentico and will be helping the technical community by providing guidance and best practices for all areas of the product. I might also do some karaoke. We'll see how the night goes...