Building Xamarin Mobile Application By Analyzing Customer Feedback Using Sentiment Analysis API

Introduction

Sentiment Analysis seeks to understand a subject’s attitude or emotional reaction towards a specific topic or brand. Sentiment Analysis does not have to be complicated and technical. It could be something as simple as getting a person in your team to find what is being said about your brand and product on the Review page and identify how much of it is good and how much of it isn’t. There is no need for a big budget and developing complicated software, the cognitive service text Analytics API is a cloud-based service that provides advanced natural language processing over raw text, and includes four main functions: sentiment analysis, key phrase extraction, language detection, and entity linking.

Building Xamarin Mobile Application With Analyzing Customer Feedback Using Sentiment Analysis API 

Most of the companies and brands now use sentiment analysis to find out what people are saying about them on social media. A bad review on social media can destroy a brand’s reputation if ignored or poorly handled. They aren’t simply rating their experience with 1 star or 5 stars. They’re also expressing their thoughts, feelings, expectations in free form text. This can be challenging to handle, especially if your company is getting a lot of feedback. When you have tens or even hundreds of thousands of pieces of feedback to read and manage, it's easy to use a cognitive text analytics service API.

Building Xamarin Mobile Application With Analyzing Customer Feedback Using Sentiment Analysis API 

The Sentiment Analysis API evaluates text input and returns a sentiment score for each document, ranging from 0 (negative) to 1 (positive). This capability is useful for detecting positive and negative sentiment in social media, customer reviews, and discussion forums. Content is provided by you, models and training data are provided by the service.

Currently, Sentiment Analysis supports English, German, Spanish, and French. Other languages are in the preview. In this article, I will show how we can integrate sentiment API from Xamarin Mobile application using visual studio 2019

Building Xamarin Mobile Application With Analyzing Customer Feedback Using Sentiment Analysis API 
 

Text Analytics API Price

The Text Analytics API can be purchased in units of the S0-S4 tier at a fixed price. Each unit of a tier comes with included quantities of API transactions. If the user exceeds the included quantities, overages are charged at the rate specified in the pricing table below. These overages are prorated and the service is billed on a monthly basis. The included quantities in a tier are reset each month. In the S tier, the service is billed for only the amount of Text Records submitted to the service. You can read more about pricing based on country check out here.

Building Xamarin Mobile Application With Analyzing Customer Feedback Using Sentiment Analysis API 

Create Text Analytics API Key

You need to create an Azure account, generate API key and endpoint URL based region for implementation to the Xamarin Mobile application.

Step 1

Create free Azure subscription and log in to the portal 

Step 2

Create On “+ Create a resource “> Under Azure Marketplace, select AI + Machine learning and discover the list of available featured. > Select “Text Analytics”
 
Building Xamarin Mobile Application With Analyzing Customer Feedback Using Sentiment Analysis API 

Step 3

On the create page, provide the name, pricing, resource group and click on "Create".
 
Building Xamarin Mobile Application With Analyzing Customer Feedback Using Sentiment Analysis API 

Step 4

Wait for a few seconds. After the Cognitive Services account is successfully deployed, click the notification or tile in the dashboard to view the account information. You can copy the Endpoint URL and Key in the Overview section for API calls in our Xamarin applications.
 
Building Xamarin Mobile Application With Analyzing Customer Feedback Using Sentiment Analysis API 
 

Build Xamarin Forms Application using Visual Studio 2019

Let's start with creating a new Xamarin Forms Project using Visual Studio 2019. When accessing Visual Studio 2019 for the first time, you will come across a new interface for opening a creating the projects.

Open Run >> Type “Devenev.Exe” and enter >> Create New Project (Ctrl+Shift+N) or select open recent application.

Building Xamarin Mobile Application With Analyzing Customer Feedback Using Sentiment Analysis API 

The available templates will appear on a window like below. Select Xamarin Forms application with different mobile platforms.

Building Xamarin Mobile Application With Analyzing Customer Feedback Using Sentiment Analysis API 

Provide project name, location, and solution name and configure a new project screen,

Building Xamarin Mobile Application With Analyzing Customer Feedback Using Sentiment Analysis API 

Select as Blank apps and select the platform.

Building Xamarin Mobile Application With Analyzing Customer Feedback Using Sentiment Analysis API 

The Solution will be created with all the platform and PCL projects.

Building Xamarin Mobile Application With Analyzing Customer Feedback Using Sentiment Analysis API 
 

PCL UI Design

The UI will have a few elements on the screen and overlay the content view window. Editor control is for providing user input value and overlay window is for showing the result.

You can add Newtonsoft.JSON to solutions. Right-click on Solutions > Manage NuGet Packages > select Newtonsoft.Json from the Browse tab > click "Install".

  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"  
  3.              xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"  
  4.              xmlns:local="clr-namespace:MobileFeedback"  
  5.              x:Class="MobileFeedback.MainPage">  
  6.     <ContentPage.Content>  
  7.         <AbsoluteLayout>  
  8.             <!-- Normal Page Content -->  
  9.             <StackLayout AbsoluteLayout.LayoutBounds="0, 0, 1, 1"  
  10.                  AbsoluteLayout.LayoutFlags="All">  
  11.                 <Image Source="product.gif"   VerticalOptions="Start" HorizontalOptions="Start"  Margin="0,0,0,0" ></Image>  
  12.                 <Editor x:Name="txtfeedback" WidthRequest="100"  HeightRequest="200"></Editor>  
  13.                 <Button Text="Submit" Clicked="Submit_Clicked"></Button>  
  14.             </StackLayout>  
  15.             <!-- Overlay -->  
  16.             <ContentView x:Name="overlay"  
  17.                  AbsoluteLayout.LayoutBounds="0, 0, 1, 1"  
  18.                  AbsoluteLayout.LayoutFlags="All"  
  19.                  IsVisible="False"  
  20.                  BackgroundColor="#C0808080"  
  21.                  Padding="10, 0">  
  22.                 <StackLayout Orientation="Vertical"   
  23.                    BackgroundColor="White"   
  24.                    HeightRequest="175"   
  25.                    WidthRequest="300"   
  26.                    HorizontalOptions="Center"   
  27.                    VerticalOptions="Start"   
  28.                    Margin="0,20,0,0" >  
  29.                     <Image x:Name="imgstatus" WidthRequest="70" HeightRequest="70"></Image>  
  30.                     <Label Text="" x:Name="lblStatus"></Label>  
  31.                     <StackLayout Orientation="Horizontal" HorizontalOptions="Center">  
  32.                         <Button Text="OK" FontSize="Small"  
  33.                         VerticalOptions="CenterAndExpand"  
  34.                         HorizontalOptions="Center"  
  35.                         Clicked="OnOKButtonClicked" />  
  36.                     </StackLayout>  
  37.                 </StackLayout>  
  38.             </ContentView>  
  39.         </AbsoluteLayout>  
  40.     </ContentPage.Content>  
  41. </ContentPage>  

Create Document Entity Class

Create class for Document class, it will deserialize the response and return an object of type TextAnalyticsResponse. The response format defined by the API looks like the below document entity:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Text;  
  4.   
  5. namespace MobileFeedback  
  6. {   
  7.      class Document  
  8.     {  
  9.         public string Id { getset; }  
  10.         public double? Score { getset; }  
  11.     }  
  12.     class TextAnalyticsResponse  
  13.     {  
  14.         public List<Document> Documents { getset; }  
  15.     }  
  16. }  

Create SentimentAnalysisHelper Helper Class

You can replace Text Analytics API service endpoint and subscription key. If you don't already have these go back to the previous steps. Below is the complete class you need to add. We have to append /sentiment to the end of the ApiUri in order to invoke the sentiment operation.

Building Xamarin Mobile Application With Analyzing Customer Feedback Using Sentiment Analysis API 
  1. using Newtonsoft.Json;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Net.Http;  
  5. using System.Text;  
  6.   
  7. namespace MobileFeedback  
  8. {  
  9.     static class SentimentAnalysisHelper  
  10.     {  
  11.         private const string ApiUri = "<API url>”;  
  12.         private const string SubscriptionKey = "<your Key>";  
  13.         private const string Text = "The food was delicious and there were wonderful staff.";  
  14.         private static readonly HttpClient Client = GetClient();  
  15.   
  16.         private static HttpClient GetClient()  
  17.         {  
  18.             var client = new HttpClient();  
  19.             client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", SubscriptionKey);  
  20.             client.DefaultRequestHeaders.Add("ContentType""application/json");  
  21.             client.DefaultRequestHeaders.Add("Accept""application/json");  
  22.             return client;  
  23.         }  
  24.         private static TextAnalyticsResponse DeserializeTextAnalyticsResponse(string json)  
  25.         {  
  26.             return JsonConvert.DeserializeObject<TextAnalyticsResponse>(json);  
  27.         }  
  28.         public static TextAnalyticsResponse GetSentiment(string text)  
  29.         {  
  30.             var body = JsonConvert.SerializeObject(new  
  31.             {  
  32.                 Documents = new object[]  
  33.                   {  
  34.         new  
  35.         {  
  36.           Text = text,  
  37.           Id = Guid.NewGuid()  
  38.         }  
  39.                   }  
  40.             });  
  41.   
  42.             using (var content = new ByteArrayContent(Encoding.UTF8.GetBytes(body)))  
  43.             {  
  44.                 var responseMessage = Client.PostAsync(ApiUri, content).Result;  
  45.                 responseMessage.EnsureSuccessStatusCode();  
  46.                 var json = responseMessage.Content.ReadAsStringAsync().Result;  
  47.                 return DeserializeTextAnalyticsResponse(json);  
  48.             }  
  49.         }  
  50.     }  
  51. }  

You can add following to the code behind in the design file. We'll add a method(GetSentiment) to call the Text Analytics API sentiment endpoint. It will deserialize the response and return an object of type TextAnalyticsResponse. The method will take a string text as input, create the request body, and then send it to the Text Analytics API using an HttpClient instance.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using Xamarin.Forms;  
  7. using System.Net.Http;  
  8. using System.Threading;  
  9.   
  10. namespace MobileFeedback  
  11. {  
  12.     public partial class MainPage : ContentPage  
  13.     {  
  14.          
  15.         public MainPage()  
  16.         {  
  17.             InitializeComponent();  
  18.              
  19.         }  
  20.   
  21.         private  void Submit_Clicked(object sender, EventArgs e)  
  22.         {  
  23.              
  24.             TextAnalyticsResponse result =  SentimentAnalysisHelper.GetSentiment(txtfeedback.Text);  
  25.             double? score = result.Documents.FirstOrDefault().Score;  
  26.             if(score < 0.5)  
  27.             {  
  28.                 imgstatus.Source = "bad.png";  
  29.                 lblStatus.Text = "This is the first time we have heard of this problem. Thank you for pointing it out to us. I assure you we will do our best to prevent it from happening again, We will contact with you regardng the issue";  
  30.             }  
  31.             else if(score > 0.5 && score < 0.9)  
  32.             {  
  33.                 imgstatus.Source = "okay.png";  
  34.                 lblStatus.Text = "We are always eager to get feedback from our customers. Thank you for taking the time to write to us.We will improve our service and our team will contact you";  
  35.             }  
  36.             else if(score> 0.9)  
  37.                 {  
  38.                 imgstatus.Source = "happy.png";  
  39.                 lblStatus.Text = "Your valuable feedback will assist us in our continuing effort to provide our users with the best possible support experience.";  
  40.             }  
  41.             overlay.IsVisible = true;  
  42.         }  
  43.         void OnOKButtonClicked(object sender, EventArgs args)  
  44.         {  
  45.   
  46.             overlay.IsVisible = false;  
  47.   
  48.         }  
  49.   
  50.         void OnCancelButtonClicked(object sender, EventArgs args)  
  51.         {  
  52.             overlay.IsVisible = false;  
  53.         }  
  54.     }  

We have completed the code for consuming TextAnalytics API. Now, we can select the platform and press F5. The output looks like below,

Building Xamarin Mobile Application With Analyzing Customer Feedback Using Sentiment Analysis API
 

Summary

In this article, you learned about consuming TextAnalytics API and automating customer feedback without using ratings. I hope this article will help you. Please leave your feedback/query using the comments box, and if you like this article, please share it with your friends.


Similar Articles