Utilizing Google’s Spell Check APIs on the Client and Server
By Donny Mack
Published: 12/15/2003
Reader Level: Intermediate
Rated: 5.00 by 4 member(s).
Tell a Friend
Rate this Article
Printable Version
Discuss in the Forums

Download the Source

Google.com provides developers a simple, but rich, set of APIs that you can use in your own application in the form of Web Services. I believe the primary reason Google does this is to enable developers to use their services without the need to make a hack, which many developers did in the past with screen scraping technologies. In this series of “Googlizing” articles, I’ll demonstrate how to use Google’s entire set of open APIs to “Googlize” your Web site — or Windows application. Some stuff you may see will be elementary, and some not so much. In every article, I’ll try to mix concept with proof of concept, illustrating how to use the Google APIs, and then showing a practical use or technique to implement them.

In Part I, “Utilizing Google’s Spell Check APIs on the Client and Server,” I’ll demonstrate how to use Google’s Spell Check API, but unlike many of the articles on this subject, I’ll show how to utilize it not only on the server, but on the client using Internet Explorer’s WebService Behavior. In addition, in the coding section of this article, you’ll notice that I implement the Google Spell Check API using a .NET Web Form, as well as a regular “old” .htm page.

Prerequisites

To follow this article, you need to do two things, if you haven't done them already. First, sign up for the Google API service. You can sign up and download the kit at:

http://www.google.com/apis/

Second, you need to download the WebService Behavior at (this is also available in the download for this project):

http://msdn.microsoft.com/library/default.asp?url=/workshop/author/webservice/overview.asp

Starting and Configuring the Project

A full C# VS.NET project that you’ll need to wire up with Internet Information Server (IIS) is included in the download. You can work with it by creating a new virtual directory in IIS, and then edit the Atomic.sln file to point to that local virtual directory. After you have the project wired up correctly, open it up. We have to edit a couple things before you can run the project.

Open the Web.config file and add your Google key in the GoogleKey application setting:

<appSettings>
    <add key="GoogleKey" value=""></add>
</appSettings>

Next open /js/client-script.js and look for the Spelling_Init() function. You need to change the HOST in the URL to that of your own machine (http://localhost:101/Atomic.Google/ to your settings):

function Spelling_Init(){
    wsInvoke.useService("http://localhost:101/Atomic.Google/Services/SpellingService.asmx?WSDL","GoogleSearchService");
}

Google Spell Check API Documentation

You can find the documentation for the Spell Check Google APIs at http://www.google.com/apis/reference.html#1_3. Basically, on the developer license:

  • You can have up to 1,000 queries a day.
  • A “dirty” string is passed in and a “clean” string returned.
  • A string can consist of 10 individual words.
Creating a Server-Side Spell Checker

Before creating the server-side Form, you must make sure you have all the right references. In Visual Studio .NET, open up your Solutions Explorer window and see if there is a Web References section. If there is, expand it and ensure that there is a Google Web Reference. If not, right-click on References and click Add Web Reference, and copy and paste the following into the URL: http://api.google.com/GoogleSearch.wsdl. This is the reference to the Google WSDL file. You’ll want to rename the reference to GoogleIt to follow along with this article.

Now that we have everything configured correctly, let’s look at some code. The primary methods for all Google APIs are in Components/Google.cs. Currently, there are just two methods, but as I go through all the APIs in this series of articles, this file will continue to grow.

The first method CheckSpelling actually invokes the Google API (see FIGURE 1), and the second formats input strings.

public static string CheckSpelling( string dirty ) {

   // Make sure a value is passed
   if ( dirty == string.Empty )
   return dirty;

   // Query is limited to 10 words or 2048 BYTES. We're not testing for bytes only word count.
   ArrayList dirtyWordGroups = GroupWords(dirty);

   GoogleIt.GoogleSearchService GIS = new GoogleIt.GoogleSearchService();
   string result = null; 
   string tmpWords = null;
   string tmpGoogleWords = null;
   bool spellingError = false;

   // split into individual words 
   for ( int i = 0; i < dirtyWordGroups.Count; i ++ ) {

   tmpWords = (string)dirtyWordGroups[i];
   int wordLength = Encoding.ASCII.GetByteCount( tmpWords );

   tmpGoogleWords = GIS.doSpellingSuggestion( Globals.GoogleKey, tmpWords );

   int isIdentical = string.Compare(tmpWords, tmpGoogleWords); 

   if ( isIdentical != 0 ) {

      if ( tmpGoogleWords == null) {
         tmpGoogleWords = tmpWords;
      }else {
         spellingError = true;
      }

   } else {

      tmpGoogleWords = tmpWords;

   }

   result += tmpGoogleWords + " ";

   } 

   if ( spellingError == false ) { //identical

      // No spelling mistakes 
      return "Good Spelling Old Chap!";

   } else {

      // Go back to school
      return result.Trim();

   }
}

FIGURE 1: The CheckSpelling method

The CheckSpelling method is pretty straightforward. We’re just taking a dirty string in, passing it to a method named GroupWords, which groups the string into groups of individual words (small enough to pass to the Google method, remember it has a maxLength of 10 words), then loops through that ArrayList invoking the Google doSpellingSuggestion() method.

Once a clean version is returned from the Google Web Service, the dirty and clean strings are compared and if they’re different we set the spellingError flag to true, indicating that there was a misspelling in the original text.

We continue down through all the words and eventually return either “Good Spelling Old Chap!”, if all the words were spelled correctly, or return the revised copy of the words indicating that there was a misspelling.

Now let’s look at the actual Web Form used in this situation. Open up ClientSpellCheck/Server.aspx. All you'll see here is a text box, two labels, a hidden field, and a submit button. Another thing you’ll notice is that there is a JavaScript file included. In this example, this file is used only for moving text from one area of the screen to another. You can open up the .js file to look it over at this time. The primary function used in the .js file is useProofed_OnCheck. Basically, this will move the spell-checked data from a label to the primary text box on the page. This is wired up in the Page_Load event:

private void Page_Load(object sender, System.EventArgs e) {
    this.UseProofed.Attributes["OnClick"] = "useProofed_OnCheck('" + this.Proofed.ClientID + "','" + this.SpellingTest.ClientID + "')";
}

The check box is wired up to invoke the client-side useProofed_OnCheck function. I know the client-script I created needs some work, so please be nice. Now load up the page, as shown in FIGURE 2.

FIGURE 2: The resulting page

Now enter the following sentences in the page: Two birdss fly to paris for lunch. It was really jst a tst of endurance. When the page posts back, you should get a pop-up message, as shown in FIGURE 3.

FIGURE 3: The error message in the Server-Side Spell Checker.

Next, click OK and the page should dynamically change, as shown in FIGURE 4.

FIGURE 4: The corrected sentences in the Server-Side Spell Checker.

Notice a label with the corrected spelling shows up along with a check box. If you check this box, the data is pushed up to the text box; uncheck it and it should return to the original text.

Creating a Client-Side Spell Checker

So, as you’ve seen, it’s not too difficult to use the Google Spell Check APIs. Next, you’ll learn how to use them from a client’s browser. Instead of posting back, you’ll access a Web Service from the client’s browser, which returns the data directly back. This is accomplished using a WebService Behavior. Because this article is about invoking the Web Service rather than using the WebService Behavior, I’m not going to spend much time talking about it. (If you’d like to see a full article on utilizing the WebService Behavior, let me know and I’ll make it happen.

There are a few things in the Web page I would like to discuss. First, take a look at the code (see FIGURE 5).

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
    <title>Atomic.Google Client-Side SpellChecker</title>
     <script language="javascript" src="/Atomic.Google/js/client-scripts.js"></script>
</HEAD>
<BODY ID="wsInvoke" STYLE="BEHAVIOR:url(/Atomic.Google/Htc/webservice.htc)" onresult="OnSpellCheck();"
     onload="Spelling_Init();">
<form id="Form1" method="post" runat="server" onsubmit="return CanSubmitToServer()">
     <table ID="Table1">
         <tr>
             <td>
                 This example illustrates how to implement the Google Spellcheck API from a client-side script.
             </td>
         </tr>
         <tr>
             <td>
                 <textarea id="SpellingTest" Name="SpellingTest" rows=10 cols= 40style="width=500px"></textarea>
             </td>
         </tr>
         <tr>
             <td>
                 <span
                     ID="Proofed"
                     style="visibility:hidden; width=500px; BORDER-RIGHT: black 1px solid; BORDER-TOP: black 1px solid; BORDER-LEFT: black 1px solid; BORDER-BOTTOM: black 1px solid; BACKGROUND-COLOR: whitesmoke">
                 </span>
                 <br>
                 <span
                     style="FONT-SIZE:10pt;VISIBILITY:hidden"
                     id="checkMove"
                     name="checkMove">
 
                     <input
                         id="UseProofed"
                         type="checkbox"
                         onclick="useProofed_OnCheck('Proofed','SpellingTest')" NAME="UseProofed">
                     <label for="UseProofed">Use Proofed</label>
 
                 </span>
                 <input type="hidden" id="originalText" NAME="originalText">
             </td>
         </tr>
         <tr>
             <td>
                 <input type=button value="Spell Check" onclick="checkSpelling(document.all['SpellingTest'].value)" ID="Button1" NAME="Button1">
             </td>
         </tr>
     </table>
</form>
</BODY>
</HTML>

FIGURE 5: The Web Form/Web Page

Check out the <body> element:

<BODY ID="wsInvoke" STYLE="BEHAVIOR:url(/Atomic.Google/Htc/webservice.htc)" onresult="onmyresult();" onload="Spelling_Init();">

Within the <body> element, I load the WebService Behavior and invoke the Spelling_Init() function of the .JS file; the one method we changed in the configuration section of this article:

function Spelling_Init(){
    wsInvoke.useService("http://localhost:101/Atomic.Google/Services/SpellingService.asmx?WSDL","GoogleSearchService");
}

The useService method just maps the Web Service to a friendly name, GoogleSearchService, which we use within the rest of the script. You’ll notice that this service doesn’t invoke the Google Service directly, but rather through a proxy service I created (found in the download). This is done primarily for security purposes. If we were to invoke the Google Service directly, we would have to put our key in the .js file, so instead I created a simple Web Service that invokes the Components/Google.cs CheckSpelling method. So, let’s load up the page and try it out (see FIGURE 6).

FIGURE 6: The initial page in the Client-Side Spell Checker.

Enter the following sentence: Two birdss fly to paris for lunch. It was really jst a tst of endurance. You should get the error message shown in FIGURE 7.

FIGURE 7: The error message in the Client-Side Spell Checker.

Click OK and the page should change, as shown in FIGURE 8.

FIGURE 8: The corrected sentences in the Client-Side Spell Checker.

So what exactly happened? Well, when the OK button is clicked, the onClick event handler is fired which invokes CheckSpelling:

function checkSpelling( obj ) {

    // Make sure that the check box isn't checked anymore:
    document.all["UseProofed"].checked = false;
    wsInvoke.GoogleSearchService.callService("CheckSpelling", obj);

}

The CheckSpelling method unchecks the UseProofed check box, in case this is a second post, and invokes the GoogleSearchService method.

Because the WebService Behavior is an asynchronous call, we have an OnSpellCheck event handler, which is wired up on the element attribute, onresult:

function OnSpellCheck() {

    canSubmitForm = "false"; 

    if (event.result.error) {

        var errorCode = event.result.errorDetail.code;
        alert("An error occured try to reach spell check service. Error Code:" + errorCode);

    } else {

        document.all["Proofed"].innerText = event.result.value ;

        if ( event.result.value == "Good Spelling Old Chap!" ) {

            document.all["Proofed"].style.visibility ="inherit";

        } else {
            window.alert('We found some issues with your spelling. We have made the changes for you and placed them in the gray box.'); 
            document.all["Proofed"].style.visibility ="visible";
            document.all["checkMove"].style.visibility = "visible";
            document.all["UseProofed"].style.visibility ="visible";

        }
    }
}

First, the error property of the result is checked. If none, we check if there were misspellings. If so, we alert the user; if not, we let them know that they’re good at spelling.

More Information

WebService Behavior Links:

Google API Links:

Conclusion

In this article, you learned how to implement the Google Web Services APIs for spell checking. There were two methods discussed: client-side and server-side. Using the server-side method, we invoked the Google Web Services directly. In the client-side method, we invoked a local Web Service using the WebService Behavior for security reasons, which invoked the Google Web Service. In the next article in this series, I’ll discuss searching using the Google APIs. I’ll explain how to use Google’s search hints to narrow or widen your search and how to cache these search results on your server.



Marketplace
(Sponsored Links)
What are the green links?
   



 
Copyright © 2007 CMP Tech LLC |
Privacy Policy (4/10/06) | Your California Privacy Rights (4/10/06) | Terms of Service | Advertising Info | About Us | Help