Make Your AJAX Apps Wiser Using Auto-Complete Functionality in Atlas

n my last article on Atlas, I gave you an introduction to the Atlas framework and showed you how to use the UpdatePanel control to update portions of pages without a server refresh. In this article, I’ll drive your Atlas abilities even further by showing you how to use the AutoCompleteExtender control to help a user complete a TextBox entry by making suggestions.

Google Suggest is a good example of this type of functionality (see Figure 1). As you type into the search text box, Google dynamically offers suggestions based on what other users have searched for.

Creating an Atlas Web Site
The first project I’d like to share with you is a TextBox control that displays a list of matching country names as you type into it.

In Visual Studio 2005, create a new Atlas Web site project and name it C:AutoCompete. In the Toolbox, verify if you have the AutoCompleteExtender control listed under the Atlas tab (see Figure 2).


Figure 1. The Google Suggest tool offers suggestions for search terms based on what other users have searched for.
?
Figure 2. The AutoCompleteExtender control in the Toolbox.

If you do not have the AutoCompleteExtender control, you can right-click on the Atlas tab in Toolbox and select Choose Items?. In the Choose Toolbox Items dialog, click on the Browse? button and select the Microsoft.Web.Atlas.dll library from C:Program FilesMicrosoft ASP.NETAtlasv2.0.50727Atlas and click Open. Ensure that the AutoCompletExtender item is checked (see Figure 3) and then click OK. The AutoCompleteExtender control should now be listed in the Toolbox.

To use the AutoCompleteExtender control in your project, drag and drop it onto the Default.aspx page. You will be prompted with a dialog asking you if you want to replace the Microsoft.Web.Atlas.dll library in the Bin folder. Click No.

Once this is done, drag and drop a TextBox control onto the page and type in the string “Enter Country Name.” The Default.aspx page now looks as shown in Figure 4.


Figure 3. Add the AutoCompleteExtender control to the Toolbox.
?
Figure 4. Populate the Default.aspx page.

Next, switch to Source View and configure the AutoCompleteExtender control. The AutoCompleteExtender control uses a Web service, which you will build in this article, to retrieve a list of values to auto-complete the control (such as a TextBox) associated with it. Hence, in the element, set the ServiceMethod attribute to “GetCountries” and the ServicePath attribute to “WebService.asmx.” The ServicePath attribute identifies the name of the Web service (the name of the .asmx file) and the ServiceMethod indicates the Web method to use.

    

Next, set the MinimumPrefixLength attribute to “1.” The MinimumPrefixLength attribute indicates the minimum number of characters that the TextBox control must have before it invokes the Web service to obtain the list of countries.

To associate a control (a TextBox control in this case) with the AutoCompleteExtender control, add a element within the element. Here you specify the control to associate with it using the TargetControlID attribute. Remember to set the Enabled attribute to “true.”

You can associate multiple controls with the AutoCompleteExtended control by simply inserting additional element(s) into the element, like this:

                                                      

For now, I just want to associate a single TextBox control with the AutoCompleteExtender control.

Adding a Web Service
The next step is to add a Web service to the current project. Right-click on the Project name in Solution Explorer and select Add New Item? (see Figure 5).

Select the Web Service item and use the default name of WebService.asmx.

Author’s Note: In this step you add a Web service to your current project. Do not add a Web Service project to the current solution. The AutoCompleteExtender control uses a Web service that is hosted within the current project.

Figure 6 shows that two files are added?WebService.vb and WebService.asmx (this name corresponds to the value set in the ServicePath attribute).


Figure 5. Here I’m adding a new Web service to the current project.
?
Figure 6. Here you can see the Web services files in the current project.

The Web service will read from a file containing a list of country names but first you need to create the file. This file will be a list of country names and it will be the basis for the Web service functionality. Compile a list of country names and put it in a text file; save the file as C:AutoCompletecountries.txt. (The code download that comes with this article includes a pre-made text file with all country names that you can use.)

The list below shows some of the countries in the list in unsorted order:

  • Monaco
  • Macau SAR (PRC)
  • Hong Kong SAR (PRC)
  • Singapore
  • Gibraltar
  • Vatican City
  • Malta
  • Bermuda
  • Maldives
  • Bahrain
  • Bangladesh

Double-click on the WebService.vb file and add the following web method:

     _       Public Function GetCountries( _          ByVal prefixText As String, _          ByVal count As Integer) _          As String()        Dim result() As String        Dim countries() As String        '---read the content of the text file---        Dim fileContents As String        fileContents = _           My.Computer.FileSystem.ReadAllText( _           "C:AutoCompletecountries.txt")        '---load the countries into the array---        countries = fileContents.Split(vbLf)        Dim listOfCountries As String = String.Empty        '---find countries being with the prefixText---        For Each country As String In countries            If country.StartsWith(prefixText, _               StringComparison.OrdinalIgnoreCase) Then                '---add the country name to the list---                listOfCountries += country & vbLf            End If        Next        '---convert the countries list into an array---        result = listOfCountries.Split(vbLf)        '---sort the array---        Array.Sort(result)        Return result    End Function

The GetCountries() Web method name corresponds to the value set in the ServiceMethod attribute. In this method, you first read the list of country names into an array and then look for country names that begin with the string specified in the PrefixText parameter. The matching country names are saved into a string and eventually converted to an array and returned to the client.

In general, to tie up the AutoCompleteExtender control with a Web service, your Web method must have the following signature:

 Public Function FunctionName( _   ByVal prefixText As String, _   ByVal count As Integer) _   As String()

The prefixText parameter will contain the text typed in the associated control (such as a TextBox). The count parameter indicates the maximum number of possible values to return to the client. You can name your function with any name you like, but the function name must be set accordingly in the ServiceMethod attribute in the element. The method returns a string array.

Testing the Application
Press F5 to test the application. In the TextBox control, notice that as you type each character a list of matching country names will be shown (see Figure 7).

A Word about Web Services
Earlier on, I mentioned that the Web service must be hosted within the same Atlas application and not as a separate Web service project. Why is this so? The reason is that Web services hosted within an Atlas application are able to generate Javascript proxies to be used by the client browser. To view the proxy generated, select the WebService.asmx file in Solution Explorer and then press F5. Append the “/js” string to the back of the URL and you should be able to see the Javascript proxy (see Figure 8).


Figure 7. Testing the application.
?
Figure 8. Viewing the Javascript proxy.

A normal Web services project (non-Atlas applications) will not support the generation of Javascript proxy. Hence, if you really need to host your Web service as a separate project, the easiest way would be to create an Atlas project and then add a Web service item to the Atlas project.

Assuming you have a separate Atlas project named AtlasWebService and it contains a Web service file named WebService.asmx, to use this web service in your current Atlas application, you would modify the ServicePath attribute as follows:

One important point to note here is that, due to security constraints, the AutoCompleteExtender control requires that both the Atlas project and the Web service must be hosted on the same server (and running on the same port number). In this example, both must be hosted by IIS. Trying to run this example using the built-in Web server in Visual Studio 2005 will not work, because different projects will run on different port numbers. If you try to connect to external web services, you will get an error. On the next page I’ll discuss a way of circumventing this restriction.

Calling External Web Services
While the AutoCompleteExtender control does not by default allow you to connect to external Web services, you can actually circumvent this restriction by using a technique known as bridging, which is described in this documentation.

However, a much simpler way to call external Web services is to call them from within your own Web service. The AutoCompleteExtender control is useful not just for auto-completing a text entry; it is also useful if you want to get an instant result based on what you type in the TextBox. For example, you might have a site that translates sentences from one language to another. Using the AutoCompleteExtender control, you can translate real-time as the user types. In this section, I will show you how this can be done.

Using the same project created in the last section, add a new Web Reference to the following Web service: http://www.webservicex.com/TranslateService.asmx?WSDL (see Figure 9). Click the Add Reference button to add the Web reference.

Author’s Note: This is a Web service that allows you to translate sentences from one language to another. However, it is sometimes unstable and hence may not work all the time. However, you can easily replace this with another translation Web service you may find on the Web.

In Default.aspx page, add a new AutoCompleteExtender control and a new TextBox control named TextBox2 and then enter the following string “Enter a string to translate” (see Figure 10).


Figure 9. Add a Web Reference to the Web service.
?
Figure 10. Add the second set of AutoCompleteExtender and TextBox controls.

In Source View, configure the AutoCompleteExtender control as follows:

         ServiceMethod="Translate"            ServicePath="WebService.asmx" MinimumPrefixLength="1">                            Enter a string to translate

In the WebService.vb file, add the following Translate() Web method:

     _    Public Function Translate( _       ByVal prefixText As String, _       ByVal count As Integer) _       As String()        Dim result(3) As String        Dim ws As New com.webservicex.www.TranslateService        result(0) = ws.Translate( _           com.webservicex.www.Language.EnglishTOChinese, prefixText)        result(1) = ws.Translate( _           com.webservicex.www.Language.EnglishTOJapanese, prefixText)        result(2) = ws.Translate( _           com.webservicex.www.Language.EnglishTOFrench, prefixText)        result(3) = ws.Translate( _           com.webservicex.www.Language.EnglishTOKorean, prefixText)        Return result    End Function

The Translate() Web method basically calls the translation Web service and translates whatever the user types into four different languages?Chinese, Japanese, French, and Korean.

Press F5 to test the application. Type a string to translate into the second TextBox and observe that as you type the translation is performed in real time (see Figure 11).


Figure 11. The translation is done in real time.
?
Figure 12. The translation will only take place if you end your sentence with a “.”.

The speed at which the translation is performed is dependent on the network latency of the Web service as well as how many users are viewing your page at the moment. The downside to this application is that every time the user types a new character the entire string is sent to the Web service for translation, which is not a very sensible thing to do. To remedy this, it might be better to translate the sentence only if the user ends the sentence with a “.”. This can be fixed easily by performing a check in the Web method:

     _    Public Function Translate( _       ByVal prefixText As String, _       ByVal count As Integer) _       As String()        If Not prefixText.EndsWith(".") Then            Return Nothing        End If        Dim result(3) As String        Dim ws As New com.webservicex.www.TranslateService        result(0) = ws.Translate( _           com.webservicex.www.Language.EnglishTOChinese, prefixText)        result(1) = ws.Translate( _           com.webservicex.www.Language.EnglishTOJapanese, prefixText)        result(2) = ws.Translate( _           com.webservicex.www.Language.EnglishTOFrench, prefixText)        result(3) = ws.Translate( _           com.webservicex.www.Language.EnglishTOKorean, prefixText)        Return result    End Function

Now the Web service will only be invoked whenever the user ends the sentence with a “.” (see Figure 12).

Figure 13. This video shows both the country name suggestion and the translation feature in action. Click the play button twice to start the video.

In this article, you learned how to use the AutoCompleteExtender control to enhance the usability of your Web application, specifically by trying to offer suggestions on whatever the user is typing. You have also learned how to invoke external Web services by calling them in your own Web service. In future articles on Atlas, I will show you how to perform drag-and-drop on your Web pages using Atlas.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: