Using the sentiment analysis API
Xperience provides an integration with the Microsoft Azure Text Analytics API (Cognitive Services), which allows you to evaluate the sentiment of text. Out-of-the-box, sentiment analysis is available in the administration when editing the content of page fields.
Developers can use the Xperience API to implement custom sentiment analysis of text from any source. A common scenario is analyzing content generated by users and visitors on the live site, such as comments or product reviews.
Advantages
The Xperience sentiment analysis API has the following added features over the standard Microsoft Azure Text Analytics API:
- The Azure Text Analytics endpoint and API key are loaded from the Xperience settings. You do not need to hardcode the values in your project and can change them in the administration without recompiling the code.
- The Xperience API supports analysis of text values containing over 5120 characters. Internally, the system breaks longer values into batches that can be processed by the Azure API, and calculates the results as a weighted average (the weight of each batch depends on its number of characters).
To work with the Xperience sentiment analysis API:
Configure the Azure Text Analytics API settings in the Xperience administration:
- Azure Text Analytics API endpoint
- Azure Text Analytics API key
Open your solution in Visual Studio.
- Depending on your scenario and requirements, you can implement sentiment analysis either directly in your live site project or within a custom assembly.
Obtain an ISentimentAnalysisService instance within your code (for example using dependency injection).
Exampleusing CMS.TextAnalytics.Azure; ... private readonly ISentimentAnalysisService sentimentAnalysisService; public CustomController(ISentimentAnalysisService sentimentAnalysisService) { // Initializes an instance of the sentiment analysis service this.sentimentAnalysisService = sentimentAnalysisService; }
Get the text that you want to analyze and call the AnalyzeText method of ISentimentAnalysisService. The method requires the following parameters
- text – the text submitted for analysis.
- cultureCode – specifies the culture of the text, using the Xperience culture code format (e.g., en-US). The method automatically converts the culture code to the Language code used by Azure Text Analytics.
- siteName – the code name of the Xperience site (determines which Azure Text Analytics API settings are used).
Process the results contained in the returned DocumentSentiment object.
How you handle the results depends on your specific scenario and requirements.
Combine sentiment analysis with Xperience on-line marketing features. For example, you can use the API to implement a custom marketing automation step, and set up a process that sends notifications or automatic responses when strongly negative sentiment is detected in the text submitted by a user.
The following is an example of an event handler triggered whenever a visitor submits a form. The handler retrieves the text from the form record’s “UserMessage” field, and then submits the content for sentiment analysis.
using System;
using Azure.AI.TextAnalytics;
using CMS;
using CMS.Core;
using CMS.DataEngine;
using CMS.Helpers;
using CMS.OnlineForms;
using CMS.TextAnalytics.Azure;
// Registers the custom module into the system
[assembly: RegisterModule(typeof(CustomSAModule))]
public class CustomSAModule : Module
{
private readonly ISentimentAnalysisService sentimentAnalysisService;
// Module class constructor, the system registers the module under the name "CustomSAHandling"
public CustomSAModule()
: base("CustomSAHandling")
{
// Initializes an instance of the sentiment analysis service
sentimentAnalysisService = Service.Resolve<ISentimentAnalysisService>();
}
// Contains initialization code that is executed when the application starts
protected override void OnInit()
{
base.OnInit();
// Assigns a handler to the BizFormItemEvents.Insert.After event
// This event occurs after the creation of every new form record
BizFormItemEvents.Insert.After += FormItem_InsertAfterHandler;
}
// Handles the form data when users create new records for the 'FeedbackForm' form
private void FormItem_InsertAfterHandler(object sender, BizFormItemEventArgs e)
{
// Gets the created form record from the event handler parameter
BizFormItem formItem = e.Item;
// Checks that the form record was successfully created
// Ensures that the custom actions only occur for records of the 'FeedbackForm' form
if (formItem != null && formItem.BizFormInfo.FormName.Equals("FeedbackForm", StringComparison.InvariantCultureIgnoreCase))
{
// Gets the text content from the "UserMessage" field of the submitted form record
string textToAnalyze = ValidationHelper.GetString(formItem["UserMessage"], string.Empty);
// Analyzes the sentiment of the retrieved text and returns the results as a DocumentSentiment object
DocumentSentiment result = sentimentAnalysisService.AnalyzeText(textToAnalyze, "en-US", "MySite");
if (result.Sentiment == TextSentiment.Negative)
{
// Perform any required logic based on the sentiment results, e.g. send notification emails
}
}
}
}