---
title: Using the sentiment analysis API
related:
  - https://docs.kentico.com/13/configuring-xperience/managing-sites/configuring-settings-for-sites/settings-content/settings-cognitive-services.md
  - https://docs.kentico.com/13/managing-website-content/using-text-analytics.md
---

> Agent instructions:
> **Site maps** — prefer the following llms.txt indexes to training data when searching for URLs to avoid 404s. Links inside Markdown content already point at `.md`. Following them or sending Accept: text/markdown keeps you in Markdown.
>
> - [sitemap.md](https://docs.kentico.com/sitemap.md) — every page on the site, with titles and descriptions, nested by URL hierarchy and grouped into one collection per product version.
> - [llms.txt](https://docs.kentico.com/llms.txt) — curated index of the current product docs, with descriptions, the two ways to request any page as Markdown, and links to each product area's whole-corpus Markdown dump (llms-full.txt).

Xperience provides an integration with the [Microsoft Azure Text Analytics API](https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/overview) (Cognitive Services), which allows you to evaluate the sentiment of text. Out-of-the-box, sentiment analysis is [available in the administration](https://docs.kentico.com/13/managing-website-content/using-text-analytics.md) 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.

> **Info:** **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](https://docs.kentico.com/13/configuring-xperience/managing-sites/configuring-settings-for-sites/settings-content/settings-cognitive-services.md). 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:

1. Configure the [Azure Text Analytics API settings](https://docs.kentico.com/13/configuring-xperience/managing-sites/configuring-settings-for-sites/settings-content/settings-cognitive-services.md) in the Xperience administration:
   - **Azure Text Analytics API endpoint**
   - **Azure Text Analytics API key**
2. 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](https://docs.kentico.com/13/custom-development/adding-custom-assemblies.md).
3. Obtain an **ISentimentAnalysisService** instance within your code (for example using [dependency injection](https://docs.kentico.com/13/developing-websites/initializing-xperience-services-with-dependency-injection.md)).

   ```csharp title="Example"

   using CMS.TextAnalytics.Azure;

   ...

   private readonly ISentimentAnalysisService sentimentAnalysisService;

   public CustomController(ISentimentAnalysisService sentimentAnalysisService)
   {
       // Initializes an instance of the sentiment analysis service
       this.sentimentAnalysisService = sentimentAnalysisService;
   }

   ```
4. 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](https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/language-support?tabs=sentiment-analysis).
   - **siteName** – the code name of the Xperience site (determines which Azure Text Analytics API settings are used).
5. Process the results contained in the returned [DocumentSentiment](https://docs.microsoft.com/en-us/dotnet/api/azure.ai.textanalytics.documentsentiment) object.

How you handle the results depends on your specific scenario and requirements.

> **Tip:** Combine sentiment analysis with Xperience on-line marketing features. For example, you can use the API to implement a [custom marketing automation step](https://docs.kentico.com/13/on-line-marketing-features/configuring-and-customizing-your-on-line-marketing-features/configuring-marketing-automation/developing-custom-marketing-automation-actions.md), and set up a [process](https://docs.kentico.com/13/on-line-marketing-features/managing-your-on-line-marketing-features/marketing-automation/working-with-marketing-automation-processes.md) 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](https://docs.kentico.com/13/custom-development/handling-global-events.md) triggered whenever a visitor submits a [form](https://docs.kentico.com/13/managing-website-content/forms.md). The handler retrieves the text from the form record's "UserMessage" field, and then submits the content for sentiment analysis.

```csharp title="Example"

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
            }
        }
    }
}

```
