UWP Sentiment Analysis Using Cognitive Service Text Analytics API, Azure, XAML And C#

Before reading this article, please go through the articles given below.

  1. Introduction To Universal Windows Platform (UWP) App Development Using Windows 10 And Visual Studio 2015
  2. Getting Started With Microsoft Azure Cognitive Services - Text Analytics API

Microsoft Cognitive Services (formerly Project Oxford) is a set of APIs, SDKs and Services available to developers to make their applications more intelligent, engaging and discoverable. Microsoft Cognitive Services expands on Microsoft’s evolving portfolio of machine learning APIs and enables the developers to easily add intelligent features. Microsoft Cognitive Services allows you to build apps with powerful algorithms, using a few lines of code. They work across the devices and platforms such as iOS, Android and Windows, which keep improving and are easy to set up.

Text Analytics API, as described by Microsoft, is designed to detect the sentiment, key phrases, topics and language from your text.

Sentiment - API returns a numeric score between 0 and 1. Scores close to 1 indicate positive sentiment, while scores close to 0 indicate negative sentiment. Sentiment score is generated, using classification techniques. The input features to the classifier include n-grams, features generated from part-of-speech tags and word embeddings. Currently, the following languages are supported: English, Spanish, French, and Portuguese.

After reading this article, you will learn how to do sentiment analysis, using Cognitive Service Text Analytics in Universal Windows apps development with Azure, XAML and Visual C#.

The following important tools are required to develop UWP and are as follows.

  1. Windows 10 (Recommended).
  2. Visual Studio 2015 Community Edition (It is a free software available online).
  3. Cognitive Service Text Analytics API Key, using Azure (Getting Started With Microsoft Azure Cognitive Services - Text Analytics API)

Now, we can discuss step by step app development.

Step 1

Open Visual Studio 2015 -> Start -> New Project-> Select Universal (under Visual C#->Windows)-> Blank app -> Give the suitable name for your app (UWPTextAnalySentiment)->OK.

prvn_kumar13

After choosing the Target and minimum platform version your Windows Universal Application will support, the project creates App.xaml and MainPage.xaml.

prvn_kumar13

Step 2

Add a TextBlock control, change the Name and text property for Title.

prvn_kumar13

Add a TextBlock control, change the Name and Text property for caption.

prvn_kumar13

Add a TextBox control, change the Name and clear the Text property to get the input text.

prvn_kumar13

Add a Button control, set the Name and add the Edit icon for sentiment analysis.

Microsoft Cognitive Services

Step 3

Add GridView Resources, using the code, mentioned below.

  1. <Grid.Resources>  
  2.     <CollectionViewSource x:Name="SentimentCol" Source="{x:Bind SentimentResults}" IsSourceGrouped="False" /> </Grid.Resources>  
Add a GridView control and set the ItemSource properties.
  1. <GridView x:Name="gvSentiment" ItemsSource="{Binding Source={StaticResource SentimentCol}}" SelectionMode="None" IsItemClickEnabled="False" HorizontalAlignment="Left" Height="276" Margin="96,233,0,0" VerticalAlignment="Top" Width="1054">  
Microsoft Cognitive Services

Add the code, mentioned below for Grid View Item Template for Phrase list.
  1. <GridView.ItemTemplate>  
  2.     <DataTemplate>  
  3.         <Border Background="AliceBlue" Width="330" Height="38" Margin="8">  
  4.             <Grid>  
  5.                 <Grid.ColumnDefinitions>  
  6.                     <ColumnDefinition Width="auto" />  
  7.                     <ColumnDefinition/> </Grid.ColumnDefinitions>  
  8.                 <Grid Grid.Column="1" Margin="3,3,3,10">  
  9.                     <Grid.RowDefinitions>  
  10.                         <RowDefinition Height="auto" /> </Grid.RowDefinitions>  
  11.                     <StackPanel Margin="0,0,0,-143">  
  12.                         <TextBlock TextWrapping="Wrap" Text="{Binding stco.Scores}" Style="{StaticResource CaptionTextBlockStyle}" Height="28" /> </StackPanel>  
  13.                 </Grid>  
  14.             </Grid>  
  15.         </Border>  
  16.     </DataTemplate>  
  17. </GridView.ItemTemplate>  
Microsoft Cognitive Services

Step 4

Add the Click event method for Analyze button.

Microsoft Cognitive Services

Step 5

Open (double click) the file MainPage.xaml in Solution Explorer and add Newtonsoft.Json reference in the project. Right click your project (UWPTextAnalySentiment) and select Manage NuGet Packages.

Microsoft Cognitive Services

To add Newtonsoft.Json Reference, choose Browse and search Newtonsoft.Json, select the package and install it.

Microsoft Cognitive Services

Reference is added to your project.

Microsoft Cognitive Services

Note

Automatically, the code mentioned below will be generated in XAML code view, while we are done in the design view.
  1. <Page x:Class="UWPTextAnalySentiment.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:UWPTextAnalySentiment" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d">  
  2.     <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">  
  3.         <Grid.Resources>  
  4.             <CollectionViewSource x:Name="SentimentCol" Source="{x:Bind SentimentResults}" IsSourceGrouped="False" /> </Grid.Resources>  
  5.         <TextBlock x:Name="tblTitle" HorizontalAlignment="Left" Margin="337,97,0,0" TextWrapping="Wrap" Text="UWP Cognitive Service Text Analytics - Sentiment Demo" VerticalAlignment="Top" FontWeight="Bold" FontSize="22" />  
  6.         <TextBlock x:Name="tblTExt" HorizontalAlignment="Left" Margin="106,162,0,0" TextWrapping="Wrap" Text="Enter Your Text for Sentiment Analysis" VerticalAlignment="Top" FontSize="20" FontWeight="Bold" />  
  7.         <TextBox x:Name="txtInput" HorizontalAlignment="Left" Margin="505,162,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="566" FontSize="20" />  
  8.         <Button x:Name="btnSentiment" HorizontalAlignment="Left" Margin="1106,164,0,0" VerticalAlignment="Top" RenderTransformOrigin="3.6,0.312" ToolTipService.ToolTip="Click to Key Phrase" Click="btnSentiment_Click">  
  9. <SymbolIcon Symbol="Find"></SymbolIcon>  
  10. </Button>  
  11.         <GridView x:Name="gvSentiment" ItemsSource="{Binding Source={StaticResource SentimentCol}}" SelectionMode="None" IsItemClickEnabled="False" HorizontalAlignment="Left" Height="276" Margin="96,233,0,0" VerticalAlignment="Top" Width="1054">  
  12.             <GridView.ItemTemplate>  
  13.                 <DataTemplate>  
  14.                     <Border Background="AliceBlue" Width="330" Height="38" Margin="8">  
  15.                         <Grid>  
  16.                             <Grid.ColumnDefinitions>  
  17.                                 <ColumnDefinition Width="auto" />  
  18.                                 <ColumnDefinition/> </Grid.ColumnDefinitions>  
  19.                             <Grid Grid.Column="1" Margin="3,3,3,10">  
  20.                                 <Grid.RowDefinitions>  
  21.                                     <RowDefinition Height="auto" /> </Grid.RowDefinitions>  
  22.                                 <StackPanel Margin="0,0,0,-143">  
  23.                                     <TextBlock TextWrapping="Wrap" Text="{Binding stco.Scores}" Style="{StaticResource CaptionTextBlockStyle}" Height="28" /> </StackPanel>  
  24.                             </Grid>  
  25.                         </Grid>  
  26.                     </Border>  
  27.                 </DataTemplate>  
  28.             </GridView.ItemTemplate>  
  29.         </GridView>  
  30.     </Grid>  
  31. </Page>  
Step 6

Add the namespaces, mentioned below in Mainpage.xaml.cs for sentiment analysis,
  1. using System.Net.Http;  
  2. using System.Threading.Tasks;  
  3. using Newtonsoft.Json.Linq;  
  4. using System.Collections.ObjectModel;  
  5. using System.Net.Http.Headers;  
  6. using System.Text;  
Step 7

Add the Text Analytics Client keys. It uses Azure Service and generates it (For More Information, please refer the article Getting Started With Microsoft Azure Cognitive Services - Text Analytics API).

Text Analytics API – Sentiment Analysis endpoint

https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/sentiment?

Add the code, mentioned below with Azure generated key for sentiment text analytics,
  1. public class sentimentc {  
  2.     public string Scores {  
  3.         get;  
  4.         set;  
  5.     }  
  6.     public string Id {  
  7.         get;  
  8.         set;  
  9.     }  
  10. }  
  11. public class Kpcol {  
  12.     public sentimentc stco {  
  13.         get;  
  14.         set;  
  15.     }  
  16. }  
  17. static string requestString, text;  
  18. public ObservableCollection < Kpcol > SentimentResults {  
  19.     get;  
  20.     set;  
  21. } = new ObservableCollection < Kpcol > ();  
  22. private async void btnSentiment_Click(object sender, RoutedEventArgs e) {  
  23.     text = txtInput.Text;  
  24.     var ss = await getSentimentScore();  
  25.     for (int i = 0; i < ss.Count(); i++) {  
  26.         sentimentc sc = ss.ElementAt(i);  
  27.         SentimentResults.Add(new Kpcol {  
  28.             stco = sc  
  29.         });  
  30.     }  
  31. }  
  32. static async Task < IEnumerable < sentimentc >> getSentimentScore() {  
  33.     List < sentimentc > sentli = new List < sentimentc > ();  
  34.     var client = new HttpClient();  
  35.     string language = "en";  
  36.     string[] input = new string[] {  
  37.         text  
  38.     };  
  39.     if (input != null) {  
  40.         // Request body.  
  41.         requestString = "{\"documents\":[";  
  42.         for (int i = 0; i < input.Length; i++) {  
  43.             requestString += string.Format("{{\"id\":\"{0}\",\"text\":\"{1}\", \"language\":\"{2}\"}}", i, input[i].Replace("\"""'"), language);  
  44.             if (i != input.Length - 1) {  
  45.                 requestString += ",";  
  46.             }  
  47.         }  
  48.         requestString += "]}";  
  49.     }  
  50.     // Request headers  
  51.     client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key""<Your Key>");  
  52.     var uri = "https://westus.api.cognitive.microsoft.com/text/analytics/v2.0/sentiment?";  
  53.     HttpResponseMessage response;  
  54.     // Request body  
  55.     byte[] byteData = Encoding.UTF8.GetBytes(requestString);  
  56.     using(var content = new ByteArrayContent(byteData)) {  
  57.         content.Headers.ContentType = new MediaTypeHeaderValue("application/json");  
  58.         response = await client.PostAsync(uri, content);  
  59.     }  
  60.     string content1 = await response.Content.ReadAsStringAsync();  
  61.     if (!response.IsSuccessStatusCode) {  
  62.         throw new Exception("Text Analytics failed. " + content1);  
  63.     }  
  64.     dynamic data = JObject.Parse(content1);  
  65.     if (data.documents != null) {  
  66.         for (int i = 0; i < data.documents.Count; i++) {  
  67.             sentli.Add(new sentimentc {  
  68.                 Scores = text + " Sentiment Score is : " + data.documents[i].score,  
  69.                     Id = data.documents[i].id  
  70.             });  
  71.         }  
  72.     }  
  73.     return sentli;  
  74. }  
Microsoft Cognitive Services

Step 8

Deploy your app in Local Machine and the output of UWPTextAnalySentiment app is shown below.

Microsoft Cognitive Services

After Analyzing the First text sentiment by clicking the Button

Microsoft Cognitive Services

After analyzing the text sentiment scores, the screenshot will appear, as shown below.  

Microsoft Cognitive Services

Summary

Now, you have successfully analyzed the sentiment in a given text, using Cognitive Service Text Analytics API, Azure, XAML and C# with UWP environment.

If you are interested, please read UWP Cognitive Service articles, mentioned below.
  1. Cognitive Service Bing Spell Check API Using Azure, XAML And C#
  2. Calchistogram Method In Cognitive Service Academic Knowledge API
  3. Interpret Method Output Value To Evaluate Method Expression In Cognitive Service Academic Knowledge API
  4. Cognitive Service Academic Knowledge API - Evaluate Method Using UWP With Azure, XAML And C#
  5. Cognitive Service Bing Web Search API Using UWP With Azure, XAML And C#
  6. Cognitive Service Bing Video Search API Using UWP With Azure, XAML And C#
  7. Cognitive Service Bing Image Search API Using UWP With Azure, XAML And C#
  8. Cognitive Service Bing News Search API Using UWP With Azure, XAML And C#
  9. Cognitive Service Bing AutoSuggest API Using UWP With Azure, XAML And C#
  10. Multiple People Emotions In UWP With Cognitive Service Emotion API, Azure, XAML And C#
  11. Cognitive Service Emotion API In UWP With Azure, XAML And C#
  12. Retrieving Face Attributes Using Cognitive Service Face API In UWP With Azure, XAML And C#
  13. Cognitive Service Face API, Using UWP With Azure, XAML And C#