This is the second blog post on the topic of Adaptive Experience using User Segmentation. In this blog post I will go through how to use data from Facebook to differentiate the users on location, and use this to drive the user experience.
 Adaptive Experience is about tailoring the user experience in order to better match the interests of the end user. This can have a great effect on sales, since a better match between products and user needs increases the chance of a sale.
Let’s take a look at the following scenario:
Pete Smith owns an online store selling electrical consumer goods. New Windows mobile 8 phones have arrived recently, and Pete wants to run a marketing campaign towards Norwegian users. To do this he will have to segment his end users by country, also referred to as location.
In order to differentiate between end users, he divides them into different user segments and gives the different user segments a different user experience. While those end users located in Norway will get an Ad displaying one of the newest Windows mobile phones in stock, end users from other countries will not see this particular campaign. They may be offered other products (but that is not a part of this example).
By segmenting his users and giving different user experiences to different end users, Pete is able to tailor his market campaigns towards a specific set of end users. He could segment his users by numerous things; browser, gender, age, etc  as long as he has this data available. 

This blog post describes how to set up user segmentation based on location, and how we can change the user experience in a product catalog by the use of Query Rules. The only custom made parts in this example are the web part placing the Login with Facebook button on the category page, and the web part which are fetching the end user location data from Facebook and matching it with custom properties in the user segments. I will give code examples on the most important parts of these web parts.

Content of this blog post:

This is how it’s working
Prerequisites
Create a term set defining the User Segments.
Create a custom web part that fetches the location data from facebook
Add the facebook login button to your category page
Create an image to be used as the Ad
Create a Query Rule that will activate on users from Norway
Add a web part to the category page for displaying the Ad
Verify the end result

 

While on the ContosoElectronics web site, the customer is logging into the web site using his Facebook credentials. By doing this he’s making his location-data (stored in Facebook) available to the custom made targeted content search web part. The custom web part (web part 2) fetches the location data from Facebook, and matches it against Custom Properties for User Segment Terms in the term set. When matching, the GUID for the relevant User Segment name (Norway) is added as a parameter to the search query which is sent to the index to fetch items to be presented in web part 2. A Query Rule monitors the search queries, and activates when the search parameter equals the GUID for the user segment Norway. The Query Rule is configured to return a search result (the Ad), to the web part sending the query in the first place. The Ad is a part of the result set SpecialTermResults. Another web part (web part 1) is added to the web site in order to display the Ad (Promotion). This web part does not send out search queries, but fetches results from web part 2. The result set SpecialTermResult is fetched. This contains the Ad sent from the Query Rule, and consists of a Title and an URL to the image to be promoted. Web part 2 can now display the Ad for the new Windows mobile phone.

Prerequisites

 

  • A Product catalog site collection has been created.
    • A list of products has been created
    • Navigation term set is created
    • Products list is shared with publishing site collection using XSP.
  • A publishing site collection has been created.
    • The web site is build up by a category page, and an item details page to display the items.
    • The site collection is available to anonymous users
  • Skills to create custom web parts in Visual Studio and deploy them in SharePoint as a Solution

 

Let’s see how all the different parts are configured to get this scenario working.

Create a term set defining the User Segments.

 

On your publishing site, in SharePoint, navigate to Site Settings=> Term store management => Taxonomy term store. In the Taxonomy Term Store navigation pane at the left, navigate to Managed Metadata Service => Site collection (the one mapped to the product catalog site collection). Create a new term set (User Segments). Then create the term Location, and the child terms Norway, UK and US.

 

For each child term in the Browser Type term set, click on Custom Properties tab, and add unique properties for that user segment in the Shared Properties section.

 

  • Shared Property Name: fbName.
  • Value: Set the User Agent String for that particular location.

 

E.g:

For user segment term Norway, Value= Norway.
For user segment term UK, value=United Kingdom.
For user segment term US, value=United States

 

These values have to match the location values fetched from Facebook.

 

Create a custom web part that fetches the location data from facebook

 

You will have to create your own custom solution in Visual Studio. This project is called SPCDemoWebParts. The custom web part you are creating has to be a part of this solution. In Visual Studio give the custom web part at title and in which category the web part will end up in.
T
his custom web part will be a modified ContentBySearchWebPart. This is done by sub-classing the ContentBySearchWebPart and adding the methods described below.

 


using Microsoft.SharePoint;
using Microsoft.SharePoint.Taxonomy;
using Microsoft.Office.Server.Search.WebControls;

     using Facebook;
namespace SPCDemoWebParts.TargetedContentSearch
{
    [ToolboxItemAttribute(false)]
    public partial class TargetedContentSearch : ContentBySearchWebPart
    {
    …

Note that you will also need to add some references to required assemblies for your project. To use the Facebook API from your project, you will need to download and install the Facebook SDK from http://csharpsdk.org/.

In addition to show content by search, it will also fetch the location given by Facebook. The web part will check each part for a matching custom property in the term store.

 

private void AddFacebookSegmentTerms(List<string> userSegmentTerms, TermStore termStore)
{
    var fbCookie = Page.Request.Cookies["Facebook.AccessToken"];
    if (fbCookie == null)
    {
        return;
    }
    string access_token = (string)fbCookie.Value; 
    var fb = new FacebookClient(access_token);
    // Fix for SSL issues with making web requests to Facebook API
    System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate(object sender1,
                    System.Security.Cryptography.X509Certificates.X509Certificate certificate,
                    System.Security.Cryptography.X509Certificates.X509Chain chain,
                    System.Net.Security.SslPolicyErrors sslPolicyErrors) { return true; };

 

    // User country is not available in graph api. Use fql instead.
    var result = (JsonObject)fb.Get("fql"New
    {
        q = "SELECT current_location FROM user WHERE uid=me()"
    });
    JsonArray data = (JsonArray)result["data"];
    JsonObject entry = (JsonObject)data[0];
    JsonObject location = (JsonObject)entry["current_location"];
    if (location == null)
    {
        return// User has not set location on Facebook
    }
    string country = (string)location["country"];
    TermCollection terms = termStore.GetTermsWithCustomProperty("fbName", country, false);
    if (terms.Count > 0)
    {
        var term = terms[0].Id.ToString();
        userSegmentTerms.Add(term);

        // TODO: You probably want to cache this term to avoid Facebook roundtrip
    }
  }

 

The GUID of any matching term for the location will then be added to the search query for fetching products. This is done by adding the list of GUIDs to the UserSegmentTerms property of the DataProviderWebPart.

 

private void AddMycustomProperties(object sender, BeforeSerializeToClientEventArgs e)
{     
    DataProviderScriptWebPart dataProvider = sender as DataProviderScriptWebPart;
    List<string> userSegmentTerms = new List<string>();

 

    AddUserAgentSegmentTerms(userSegmentTerms);
    dataProvider.Properties["UserSegmentTerms"] = userSegmentTerms.ToArray();
  }

 

This code assumes that you have previously obtained a Facebook access token for the given user and stored it somewhere. This example has stored it in a cookie, but you can also store it in the ASP session object or with your user data. You can find more information about obtaining an access token in the documentation for the Facebook C# SDK.
All that now remains is to stitch the AddMycustomProperties into the OnLoad method of the web part, so it’s called before the page is rendered.

 

protected override void OnLoad(EventArgs e)
{
    if (this.AppManager != null)
    {
        if (this.AppManager.QueryGroups.ContainsKey(this.QueryGroupName) &&
            this.AppManager.QueryGroups[this.QueryGroupName].DataProvider != null)
        {
            this.AppManager.QueryGroups[this.QueryGroupName].DataProvider.BeforeSerializeToClient +=
                new BeforeSerializeToClientEventHandler(AddMycustomProperties);
        }
    }
    base.OnLoad(e);
}

 

The same method can easily be used for segmenting users in other ways based on browsing history or login information.
The custom web part created shall be packaged as a solution with a .wsp extension.

You will have to upload the solution into the Public site Collection, and use it when setting up the category page, to display items in a category.

 

Upload the custom web part as a solution

 

Assuming the .wsp file is placed in C:\Temp\MyCustomWebPart.wsp

 

  • Start «SharePoint» 2013 Management Shell as Administrator
  • Run: Add-SPSolution -LiteralPath C:\temp\MyCustomWebPart.wsp
  • Run: Install-SPSolution -identity MyCustomWebPart.wsp -GACDeployment –AllWebApplications
  • In the publishing site collection, navigate to Site settings=> Site collection Administration => Site collection features:  Deactivate and activate site collection feature "Adaptive Experiences WebParts"

 

Obtain access to Facebook user location data

 

There are many ways of communicating with Facebook to retrieve user information. I will not go into details on that here, but will leave it to you to choose your own model. In order to be able to retrieve the end user location data from Facebook, the end user could log into the Contoso web page, using Facebook credentials. By doing this the end user agrees on letting the Contoso page fetch the end user’s location data from Facebook. The purpose of this action is to obtain an access_token to the end users’ Facebook profile, so that user location data can be retrieved.

 

Documentation on the subject can be found here:

http://csharpsdk.org/docs/web/getting-started
http://developers.facebook.com/docs/

 

Creation of that web part is not a part of this blog post.

We have solved it by creating a login button that will make facebook generate an access_token on behalf of the end user. Such access_tokens should not be sent over the network unencrypted.

 

Create an image to be used as the Ad

 

We need an image to be displayed as the Ad. In this example I’ve used an image of a Windows mobile 7.5 phone, and added some text to it. Place the image in the Image library in the publishing site collection.

 

Create a Query Rule that will activate on users from Norway

 

 The goal is to have the Query Rule to be activated by end users having registered their country of origin in Facebook to be Norway. When activated, the Query Rule shall place an Ad (the image placed in the Image library) at the top of every category page.
In the publishing site collection in Site Settings, navigate to Site Collection Administration=> Search Query Rules. Select your product catalog as source, before clicking on New Query Rule.

 

Set Rule Name: Mobile Ad for users from Norway.

Click on Context.

Under the section Query is performed by these user segments, click the radio button “One of these user segments”. Then click Add user segment. From the Import UI that pops up, navigate to Managed Metadata Service => Site Collection => User Segments => Location and choose the Norway term.

 

Then give the User Segment the name User Location Norway.

 

You have now mapped the Query Rule to the User Segment called User Location Norway, that again is mapped to the User segment Term Norway, which contains the value Norway, which again can be matched (by the custom web part) with the location data returned from Facebook. In other words; the query rule will execute on end-users from Norway.

 

Note: Under the section Query conditions: click on Remove Condition, as this Query Rule is not to be triggered by any (manuel) query.

 

We now have to set the Actions performed by the Query Rule.
Under the section Actions, click on Add promoted result.  Type Mobile campaign in the text box for Title, and insert the URL of the image to be displayed as the Ad in the text box for URL. This is the URL to the image placed in the Image library. Select the checkbox Render the URL as a banner instead of a hyperlink.

 

Then click Save.
The Query Rule definition now looks like this:

 

Click on Save to store the Query Rule.

Add a web part to the category page for displaying the Ad

 

In this section we shall add another web part at the top of the category page, to display our Ad.
Navigate to a category page, click on Edit page and Edit page template.
Click on Add a Web Part in the top section of the page. Select a Content search web part from the Content Rollup category. (you can also use your custom web part if that is based on a Content search web part) From the drop down menu in the upper right corner of the web part, click Edit Web Part.

 

  • Expand the Display Templates section. Under Control choose List. Under Item choose Large picture.
  • Expand the Property mappings section. Select the checkbox for “Change the mapping of managed properties for the fields in the Item Display Template”. In the Field Picture URL type URL.
  • Expand the section Settings, and in the drop down menu for Query results provided by, select the web part that this web part shall get its result from. In other words, select the custom target content search web part that is used on that category page. In the same section in the drop down menu for Result table, select SpecialTermResults. This is the result set where the Ad is placed by the Query Rule.

 

The respective sections in the web part editor shall now look like this.

 

Click OK to save the configuration

Verify the end result

 

Navigate to one of your category pages. Log into the web site using the Login with Facebook button. Users, with their location set to Norway in Facebook, will now see the Ad on top of any category page: