Xamarin.Forms - Bing Spell Check Using Cognitive Services

Xamarin.Forms - Bing Spell Check Using Cognitive Service
 
Xamarin.Forms code runs on multiple platforms - each of which has its own filesystem. This means that reading and writing files is most easily done using the native file APIs on each platform. Alternatively, embedded resources are a simpler solution to distribute data files with an app.

 
Cognitive Services

 
Xamarin.Forms - Bing Spell Check Using Cognitive Service
 
Xamarin and Cognitive Services together can infuse your apps, websites, and bots with intelligent algorithms to see, hear, speak, understand, and interpret your user needs through natural methods of communication. Also, they help you transform your business with AI today.

Use AI to solve business problems

  • Vision
  • Speech
  • Knowledge
  • Search
  • Language

Bing Spell Check API

  1. Bing Spell Check API helps users correct spelling errors and recognize the difference among names, brand names, and slang, as well as understand homophones while typing.
  2. Bing Spell Check API has developed a web-based spell-checker.
  3. Bing Spell Check API returns a list of words it does recognize, with suggested replacements.
Xamarin.Forms - Bing Spell Check Using Cognitive Service 
 
Prerequisites
  • Visual Studio 2017 or later (Windows or Mac)
  • Bing Spell Check API Key

Setting up a Xamarin.Forms Project

 
Start by creating a new Xamarin.Forms project. You’ll learn more by going through the steps yourself.
 
Visual Studio 2019 has more options in the opening window. Clone or check out the code from any repository or, open a project or solution for your computer.
 
Now, you need to click "Create a new project".
 
Xamarin.Forms - Bing Spell Check Using Cognitive Service 
 
Now, filter by Project Type: Mobile
 
Choose the Mobile App (Xamarin. forms) project under C# and Mobile.
 
Name your app. You probably want your project and solution to use the same name as your app. Put it on your preferred location for projects and click "Create".
 
Now, select the blank app and target platforms - Android, iOS and Windows (UWP).
 
Subsequently, go to the solution. In there, you get all the files and sources of your project (.NET Standard). Now, select the XAML page and double-click to open the MainPage.Xaml page.
 
You now have a basic Xamarin.Forms app. Click the Play button to try it out.
 

Get Bing Spell Check API Key

 
In this step, get Bing Spell Check API Key. Go to the following link.
 
https://azure.microsoft.com/en-in/services/cognitive-services/
 
Click "Try Cognitive Services for free".
 
Xamarin.Forms - Bing Spell Check Using Cognitive Service 
 
Now, you can choose Bing Spell Check API under Language APIs. Afterward, click "Get API Key".
 
Xamarin.Forms - Bing Spell Check Using Cognitive Service 
 
Now, the API key is activated. You can use it now.
 
Note
 
The trial key is available only for 7 days.
 
Xamarin.Forms - Bing Spell Check Using Cognitive Service

 
Setting up the User Interface

 
Go to MainPage.Xaml and write the following code.
 
MainPage.xaml
  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:XamarinCognitive"  
  5.              x:Class="XamarinCognitive.MainPage">  
  6.   
  7.     <StackLayout>  
  8.         <StackLayout>  
  9.             <StackLayout HorizontalOptions="Center" VerticalOptions="Start">  
  10.                 <Image x:Name="imgBanner" Source="banner.png" ></Image>  
  11.                 <Image Margin="0,0,0,10" x:Name="imgCognitive" HeightRequest="100" Source="cognitiveservice.png" ></Image>  
  12.                 <Label Margin="0,0,0,10" Text="Bing Spell Check" FontAttributes="Bold" FontSize="Large" TextColor="Gray" HorizontalTextAlignment="Center" ></Label>  
  13.                 <Entry x:Name="txtSearch" Placeholder="Type here.."></Entry>  
  14.                 <Button x:Name="btnCheck" WidthRequest="50" Text="Check" Clicked="BtnCheck_Clicked" />  
  15.                 <StackLayout HorizontalOptions="CenterAndExpand" Margin="10,0,0,10">  
  16.                     <ListView x:Name="suggestionsList">  
  17.   
  18.                     </ListView>  
  19.                 </StackLayout>  
  20.             </StackLayout>  
  21.         </StackLayout>  
  22.     </StackLayout>  
  23.   
  24. </ContentPage>   
Click the "Play" button to try it out.
 
Xamarin.Forms - Bing Spell Check Using Cognitive Service
 

NuGet Packages

 
Now, add the following NuGet packages.
  • Newtonsoft.Json
Add Newtonsoft.Json NuGet
 
Go to Solution Explorer and select your solution. Right-click and select "Manage NuGet Packages for Solution". Search "Newtonsoft.Json" and add Package. Remember to install it(.NET Standard).
 

Create a Model

 
In this step, you can create a model for deserializing your response.
 
ResponseModel.cs
  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Text;    
  4.     
  5. namespace XamarinCognitive  
  6. {  
  7.     public class ResponseModel  
  8.     {  
  9.         public string _type { getset; }  
  10.         public List<FlaggedToken> flaggedTokens { getset; }  
  11.     }  
  12.     public class Suggestion  
  13.     {  
  14.         public string suggestion { getset; }  
  15.         public double score { getset; }  
  16.     }  
  17.   
  18.     public class FlaggedToken  
  19.     {  
  20.         public int offset { getset; }  
  21.         public string token { getset; }  
  22.         public string type { getset; }  
  23.         public List<Suggestion> suggestions { getset; }  
  24.     }  
  25.   
  26.       
  27. }  

Bing Spell Check

 
In this step, write the following code for Bing Spell Check.
 
Note
Try out the spell check capabilities with Bing Spell Search API v7.
  1. ‘Spell’ is more aggressive in order to return better search results,
  2. ‘Proof’ is less aggressive and adds capitalization, basic punctuation, and other features to aid document creation.
MainPage.xaml.cs
  1. using Xamarin.Forms;  
  2. using Newtonsoft.Json;  
  3. using System.Net.Http;  
  4. using System.Net.Http.Headers;  
  5.   
  6. namespace XamarinCognitive  
  7. {  
  8.     public partial class MainPage : ContentPage  
  9.     {  
  10.         static string host = "https://api.cognitive.microsoft.com";  
  11.         static string path = "/bing/v7.0/spellcheck?";  
  12.         static string params_ = "mkt=en-US&mode=proof";  
  13.         static string key = "cdf8476d88*******66b08e53";  
  14.           
  15.         public MainPage()  
  16.         {  
  17.             InitializeComponent();  
  18.         }  
  19.   
  20.         private async void BtnCheck_Clicked(object sender, EventArgs e)  
  21.         {  
  22.             List<string> listSuggestions = new List<string>();  
  23.             var responseString = await SpellCheck(txtSearch.Text);  
  24.             var result = JsonConvert.DeserializeObject<ResponseModel>(responseString);  
  25.             if(result.flaggedTokens.Count!=0)  
  26.             {  
  27.                 foreach (var item in result.flaggedTokens[0].suggestions)  
  28.                 {  
  29.                     listSuggestions.Add(item.suggestion);  
  30.                 }  
  31.                 suggestionsList.ItemsSource = null;  
  32.                 suggestionsList.ItemsSource = listSuggestions;  
  33.             }  
  34.               
  35.         }  
  36.          
  37.   
  38.         //Bing Spell Check  
  39.         public async static Task<string> SpellCheck(string text)  
  40.         {  
  41.             HttpClient client = new HttpClient();  
  42.             client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", key);  
  43.             HttpResponseMessage response = new HttpResponseMessage();  
  44.             string uri = host + path + params_;  
  45.   
  46.             List<KeyValuePair<stringstring>> values = new List<KeyValuePair<stringstring>>();  
  47.             values.Add(new KeyValuePair<stringstring>("text", text));  
  48.   
  49.             using (FormUrlEncodedContent content = new FormUrlEncodedContent(values))  
  50.             {  
  51.                 content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");  
  52.                 response = await client.PostAsync(uri, content);  
  53.             }  
  54.   
  55.             string client_id;  
  56.             if (response.Headers.TryGetValues("X-MSEdge-ClientID"out IEnumerable<string> header_values))  
  57.             {  
  58.                 client_id = header_values.First();  
  59.                 Console.WriteLine("Client ID: " + client_id);  
  60.             }  
  61.   
  62.             string contentString = await response.Content.ReadAsStringAsync();  
  63.   
  64.             return contentString;  
  65.         }  
  66.   
  67.           
  68.     }  
  69. }   
Click the "Play" button to try it out.
 
Xamarin.Forms - Bing Spell Check Using Cognitive Service
 
I hope you have understood how to detect and correct spelling mistakes in your app using Cognitive Service Bing Spell Check API in Xamarin.Forms.
 
Thanks for reading. Please share your comments and feedback. Happy Coding :)


Similar Articles