Understanding the sentiment of an email or text message can be difficult. Someone may send a message, intending for it to be encouraging, but it may be accidentally interpreted as mean or condescending.

Luckily, Microsoft’s Text Analytics Service can help avoid any confusion.

Text Analytics Service

Microsoft’s Cognitive Services team have created the Sentiment Analysis API that uses machine learning to determine the text sentiment. And the best part is, you don’t need to be machine learning experts to use it.

You just submit the text in a POST Request, specifying the text’s language and a GUID Id.

Then the API returns back its sentiment score:

The sentiment score ranges between 0 and 1.

Scores close to 0 indicate negative sentiment, while scores close to 1 indicate positive sentiment.

Now let’s add it to a Xamarin app.

Sentiment Analysis + Xamarin

Let’s upgrade a Xamarin app to include text sentiment analysis.

The completed Xamarin.Forms app can be found here: https://github.com/brminnick/SentimentAnalysis.

1. Generate Text Analytics API Key

First, you’ll need to generate a Text Analytics API Key using the Azure Portal

  1. Navigate to the Azure Portal
  2. On the Azure Portal, select +Create a Resource
  3. In the New window, select AI + Machine Learning
  4. Use Featured frame to select Text Analytics
  5. Once the Create window opens, make the following selections:
    • Name: [Create a unique resource name]
    • Subscription: [Select your Azure subscription]
    • Location: [Select the location closest to you]
    • Pricing Tier: F0 (5K Transactions per 30 days)
      • This is a free tier
    • Resource Group: [Create a unique resource group name]
  6. Use the Create window to select Create
  7. On the Azure Portal, select the bell-shaped notification icon
  8. Stand by while the Notifications window says Deployment in progress…
  9. Once the deployment has finished, on the Notifications window, select Go to resource
  10. On the Resource page, select Keys and locate KEY 1
    • We will use this API Key in our app
  11. In the Resource page, select Overview and locate the Endpoint
    • We will use this Url in our app

2. Install NuGet Packages

Next, let’s add the following NuGet Packages to our Xamarin app. Make sure to install these in each C# Project, including the .NET Standard project, the iOS-specific project, and Android-specific project:

Microsoft.Azure.CognitiveServices.Language.TextAnalytics v2.1.0-preview
Newtonsoft.Json v11.0.2

The TextAnalytics SDK is a library that contains all of the boiler-plate code necessary for accessing the TextAnalytics API, including the C# Models and the HttpClient logic. You aren’t required to use the SDK, but it certainly saves you from writing many lines of code.

3. Implement the Sentiment Service

Now let’s implement the Sentiment Service in our Xamarin app.

This code leverages the TextAnalytics SDK’s helper classes which call the Sentiment API. This allows us to implement a Sentiment Service with just a few lines of code.

Make sure to add your API KEY and your Base Url from your Azure Text Analytics resource.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.CognitiveServices.Language.TextAnalytics;
using Microsoft.Azure.CognitiveServices.Language.TextAnalytics.Models;
using Microsoft.Rest;

namespace SentimentAnalysis
{
    public static class SentimentService
    {
        //Example Base Url: https://westus.api.cognitive.microsoft.com
        const string _sentimentAPIBaseUrl = “Add Your API’s Base Url Here”;
        const string _textSentimentAPIKey = “Add Your API Key Here”;

        //HttpClient wrapper for accessing the TextAnalytics API
        readonly static TextAnalyticsClient _textAnalyticsApiClient = new TextAnalyticsClient(new ApiKeyServiceClientCredentials(_textSentimentAPIKey))
        {
            Endpoint = _sentimentAPIBaseUrl
        };

        //Input the text to be analyzed and return its sentiment score. The sentiment score will range from 0 to 1, where 0 is negative sentiment and 1 is positive sentiment.
        public static async Task<double?> GetSentiment(string text)
        {
            //Create the request object to send to the TextAnalytics API
           //The request can contain multiple text inputs which you can use to batch multiple requests into one API call
            var request = new MultiLanguageBatchInput(new List<MultiLanguageInput>
            {
                { new MultiLanguageInput(id: “1”, text: text) }
            });

            //Get the sentiment results from the TextAnalytics API
            var sentimentResult = await _textAnalyticsApiClient.SentimentAsync(request);

            //Parse the sentiment score
            return sentimentResult?.Documents?.FirstOrDefault()?.Score;
        }

        //Helper class to add our API Key to the HttpRequestMessage Header
        class ApiKeyServiceClientCredentials : ServiceClientCredentials
        {
            readonly string _subscriptionKey;

            public ApiKeyServiceClientCredentials(string subscriptionKey)
            {
                _subscriptionKey = subscriptionKey;
            }

            public override Task ProcessHttpRequestAsync(HttpRequestMessage request, CancellationToken cancellationToken)
            {
                if (request is null)
                    throw new ArgumentNullException(nameof(request));

                request.Headers.Add(“Ocp-Apim-Subscription-Key”, _subscriptionKey);

                return Task.CompletedTask;
            }
        }
    }
}

Now we can connect a simple UI to our Sentiment Service and instantly know whether a message is happy or sad.

Learn More

Visit the Microsoft Docs to learn more about Cognitive Services:

Cognitive Services
Text Analytics
Sentiment Analysis API

About The Author

Brandon Minnick is a Developer Advocate at Microsoft. As a Developer Advocate, Brandon loves helping developers build cloud-connected mobile apps! Brandon loves talking about mobile and invites you to start up a conversation: @TheCodeTraveler.