DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Data Engineering
  3. Databases
  4. Xamarin.Forms: Bing Spell Check Using Cognitive Service

Xamarin.Forms: Bing Spell Check Using Cognitive Service

In this post, you will learn how to detect and correct spelling mistakes in your app using Cognitive Service's Bing Spell Check API in Xamarin.Forms.

Delpin Susai Raj user avatar by
Delpin Susai Raj
·
Mar. 05, 19 · Tutorial
Like (1)
Save
Tweet
Share
5.48K Views

Join the DZone community and get the full member experience.

Join For Free

Introduction

In this post, you will learn how to detect and correct spelling mistakes in your app using Cognitive Service Bing Spell Check API in Xamarin.Forms.

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 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. It helps users correct spelling errors, recognize the differences among names, brand names, and slang, as well as understand homophones as they are typing.
  2. It has developed a web-based spell checker.
  3. It returns a list of words it does recognize with suggested replacements.


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.

Click "Create a new project."

  1. Now, filter by Project Type: Mobile

  2. Choose the Mobile App (Xamarin. forms) project under C# and Mobile.

  3. 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."

  4. Now, select the blank app and target platforms — Android, iOS, and Windows (UWP).

  5. Subsequently, go to the solution. In there, you get all the files and sources of your project (.NET Standard). Now, select XAML page and double-click to open the MainPage.Xaml page.

  6. 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."

Now you can choose Bing Spell Check API under Language APIs. Afterward, click "Get API Key."

Now, the API key is activated. You can use it now.

Note: The trial key is only available for 7 days.

Setting up the User Interface

Go to MainPage.Xaml and write the following code.

MainPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:XamarinCognitive"
             x:Class="XamarinCognitive.MainPage">

    <StackLayout>
        <StackLayout>
            <StackLayout HorizontalOptions="Center" VerticalOptions="Start">
                <Image x:Name="imgBanner" Source="banner.png" ></Image>
                <Image Margin="0,0,0,10" x:Name="imgCognitive" HeightRequest="100" Source="cognitiveservice.png" ></Image>
                <Label Margin="0,0,0,10" Text="Bing Spell Check" FontAttributes="Bold" FontSize="Large" TextColor="Gray" HorizontalTextAlignment="Center" ></Label>
                <Entry x:Name="txtSearch" Placeholder="Type here.."></Entry>
                <Button x:Name="btnCheck" WidthRequest="50" Text="Check" Clicked="BtnCheck_Clicked" />
                <StackLayout HorizontalOptions="CenterAndExpand" Margin="10,0,0,10">
                    <ListView x:Name="suggestionsList">

                    </ListView>
                </StackLayout>
            </StackLayout>
        </StackLayout>
    </StackLayout>

</ContentPage>

Click the play button to try it out.

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

using System;  
using System.Collections.Generic;  
using System.Text;  

namespace XamarinCognitive
{
    public class ResponseModel
    {
        public string _type { get; set; }
        public List<FlaggedToken> flaggedTokens { get; set; }
    }
    public class Suggestion
    {
        public string suggestion { get; set; }
        public double score { get; set; }
    }

    public class FlaggedToken
    {
        public int offset { get; set; }
        public string token { get; set; }
        public string type { get; set; }
        public List<Suggestion> suggestions { get; set; }
    }


}

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.

  • ‘Spell’ is more aggressive in order to return better search results,
  • ‘Proof’ is less aggressive and adds capitalisation, basic punctuation and other features to aid document creation.

MainPage.xaml.cs

using Xamarin.Forms;
using Newtonsoft.Json;
using System.Net.Http;
using System.Net.Http.Headers;

namespace XamarinCognitive
{
    public partial class MainPage : ContentPage
    {
        static string host = "https://api.cognitive.microsoft.com";
        static string path = "/bing/v7.0/spellcheck?";
        static string params_ = "mkt=en-US&mode=proof";
        static string key = "cdf8476d88*******66b08e53";

        public MainPage()
        {
            InitializeComponent();
        }

        private async void BtnCheck_Clicked(object sender, EventArgs e)
        {
            List<string> listSuggestions = new List<string>();
            var responseString = await SpellCheck(txtSearch.Text);
            var result = JsonConvert.DeserializeObject<ResponseModel>(responseString);
            if(result.flaggedTokens.Count!=0)
            {
                foreach (var item in result.flaggedTokens[0].suggestions)
                {
                    listSuggestions.Add(item.suggestion);
                }
                suggestionsList.ItemsSource = null;
                suggestionsList.ItemsSource = listSuggestions;
            }

        }


        //Bing Spell Check
        public async static Task<string> SpellCheck(string text)
        {
            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", key);
            HttpResponseMessage response = new HttpResponseMessage();
            string uri = host + path + params_;

            List<KeyValuePair<string, string>> values = new List<KeyValuePair<string, string>>();
            values.Add(new KeyValuePair<string, string>("text", text));

            using (FormUrlEncodedContent content = new FormUrlEncodedContent(values))
            {
                content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
                response = await client.PostAsync(uri, content);
            }

            string client_id;
            if (response.Headers.TryGetValues("X-MSEdge-ClientID", out IEnumerable<string> header_values))
            {
                client_id = header_values.First();
                Console.WriteLine("Client ID: " + client_id);
            }

            string contentString = await response.Content.ReadAsStringAsync();

            return contentString;
        }


    }
}

Click the Play button to try it out.

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.

More samples from GitHub.

Thanks for reading. Please share comments and feedback. Happy coding! :)

Bing xamarin.forms mobile app API

Published at DZone with permission of Delpin Susai Raj, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • 11 Observability Tools You Should Know
  • Chaos Engineering Tutorial: Comprehensive Guide With Best Practices
  • Cloud Performance Engineering
  • A Gentle Introduction to Kubernetes

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: