To read the article online, visit http://www.4GuysFromRolla.com/articles/030503-1.2.aspx

Searching Google Using the Google Web Service, Part 2

By Scott Mitchell


  • Read Part 1

  • While the previous live demo illustrates how to call the Google Web service to perform a search, it is fairly limited in that it only displays the first 10 records of a predefined search query. In this second part we'll examine how to build a "pseudo Google" search engine, by creating a page that the user can enter a search query for and page through the search results.

    Building a More Functional Search Engine


    In order to create a more functional search through Google's Web service search API, let's create an ASP.NET Web page that allows the user to input the search term and provides pagination through the data. One way to accomplish this would be to mimic Google's own approach, meaning that search terms and page numbers would be placed in the querystring. That is, if the user searched for "ASP" and was viewing records 10 through 20, the URL requested might be:

    http://www.yourserver.com/Search.aspx?q=ASP&first=10&last=20

    Or something to that effect. Another option is to use postback forms. The postback approach lends itself to ASP.NET moreso than the querystring approach. However, the querystring approach has the benefit that a user can bookmark a particular search query (note that with the postback form, the postback occurs via the HTTP POST headers, meaning the actual querystring does not change when searching or paging through the search results).

    Despite the querystring approach's bookmarking advantage, I decided to implement this live demo using the postback approach. You are encouraged to implement the querystring approach if you so wish. The source code for the postback approach can be seen below:

    <script language="VB" runat="server">
      Const PAGE_SIZE as Integer = 5
    
      Sub execSearch(sender as Object, e as EventArgs)
        ViewState("startIndex") = 0
        
        DisplaySearchResults()
      End Sub
      
      
      Sub nextRecs(sender as Object, e as EventArgs)
        ViewState("startIndex") += PAGE_SIZE
        
        DisplaySearchResults()
      End Sub
      
      
      Sub prevRecs(sender as Object, e as EventArgs)
        ViewState("startIndex") -= PAGE_SIZE
        
        DisplaySearchResults()
      End Sub
    
    
      Sub DisplaySearchResults()
          searchResults.Visible = True
          
          Dim search As google.GoogleSearchService = New google.GoogleSearchService()
          Dim result as google.GoogleSearchResult
          
          result = search.doGoogleSearch("license key...", searchTerms.Text, _
                     ViewState("startIndex"), PAGE_SIZE, True, "", True, "", "", "")
          
          dlResults.DataSource = result.resultElements
          dlResults.DataBind()
          
          lblSearchResults.Text = "Viewing records " & String.Format("{0:#,###}", _
                    ViewState("startIndex")+1) & " - " & _
                    String.Format("{0:#,###}", ViewState("startIndex") + _
                    PAGE_SIZE) & " of about " & _
                    String.Format("{0:#,###}", result.estimatedTotalResultsCount) & _
                    ".  Search took " & _
                    String.Format("{0:0.000}", result.searchTime) & " sec."
                    
          btnPrev.Enabled = (ViewState("startIndex") > 0)
      End Sub  
    </script>
    
    <form runat="server">
    Enter your search term: <asp:TextBox runat="server" id="searchTerms" />
    <asp:Button runat="server" Text="Search" OnClick="execSearch" />
    <p>
    <asp:panel id="searchResults" runat="server" Visible="False">
      <table width="100%" bgcolor="#eeeeee">
      <tr><td align="right">
        <asp:Label id="lblSearchResults" runat="server" />
      </td></tr>
      </table>
    
      <asp:DataList runat="server" id="dlResults"
            Font-Name="Verdana" Font-Size="10pt">
    
        <ItemTemplate>
          <span style="font-size:15pt;font-weight:bold;">
            <%# Container.DataItem.title %>
          </span><br />
          <%# Container.DataItem.snippet %><br />
          [<a href="<%# Container.DataItem.URL %>"><%# Container.DataItem.URL %></a>]
        </ItemTemplate>
      
        <SeparatorTemplate>
          <p> </p>
        </SeparatorTemplate>
    
      </asp:DataList>
    
      <table width="100%" bgcolor="#eeeeee">
      <tr><td align="right">
        <asp:LinkButton id="btnPrev" runat="server" Text="< Prev." OnClick="prevRecs" /> |
        <asp:LinkButton id="btnNext" runat="server" Text="Next. >" OnClick="nextRecs" />
      </td></tr>
      </table>
    </asp:Panel>
    </form>
      
    [View a Live Demo!]

    The main workhorse subroutine in the above code listing is DisplaySearchResults(), which makes the Web service call, binds the results to the DataList, and displays miscellaneous information, such as the estimated number of matches found, the time to run the query, etc. This subroutine also determines whether or not the Prev. LinkButton should be enabled or not.

    Realize that when calling the Google search Web service, we must specify the starting result index and how many results we want to see in the page. That is, to view the first 10 records of a search, we would pass in 0 as the starting index and 10 as the number of records to return. To view the next 10 records, we'd simply pass in 10 as the starting index (leaving 10 as the number of records to return). Notice that the ViewState is used to maintain what the starting index number. The number of records to display per page is denoted by the constant PAGE_SIZE.

    To allow for pagination, two LinkButtons are used, which, when clicked, cause the nextRecs and prevRecs event handlers to fire. These event handlers simply update the starting record number to view and then call DisplaySearchResults().

    Conclusion


    In this article we saw how to call the Google search Web service. To use the Google Web services, we started by downloading the Google Web API Developer's Kit and then creating an account to obtain a license key. Following that, we created a proxy class based on the Google Web service's WSDL file (GoogleSearch.wsdl, which is included in the Developer's Kit download). Armed with this proxy class, we could then access the Web service with just a few lines of code from our ASP.NET Web page.

    Happy Programming!

  • By Scott Mitchell

  • Article Information
    Article Title: ASP.NET.Searching Google Using the Google Web Service, Part 2
    Article Author: Scott Mitchell
    Published Date: March 5, 2003
    Article URL: http://www.4GuysFromRolla.com/articles/030503-1.2.aspx


    Copyright 2017 QuinStreet Inc. All Rights Reserved.
    Legal Notices, Licensing, Permissions, Privacy Policy.
    Advertise | Newsletters | E-mail Offers