Geekpedia Tutorials Home

Building a C# Chat Client and Server

Building a C# Chat Client and ServerA step by step tutorial teaching you how to create your own chat client and chat server easily in C#, for local networks or the Internet.

in C# Programming Tutorials

Getting Hard Drive Information

Getting Hard Drive InformationA C# tutorial showing you how to make use of WMI to extract information on disk drives, such as model, capacity, sectors and serial number.

in C# Programming Tutorials

UPS Shipping Calculator

UPS Shipping CalculatorThis tutorial will teach you how to calculate the shipping cost based on the weight, height, length and depth of the box, the distance and the UPS service type.

in PHP Programming Tutorials

Create Your Own Rich Text Editor

Create Your Own Rich Text EditorCreating a Rich Text Editor using JavaScript is easier to do than you might think, thanks to the support of modern browsers; this tutorial will walk you through it.

in JavaScript Programming Tutorials
Search
Tutorials
Programming Tutorials
IT Jobs
From CareerBuilder

Google Search using Web Service

Tutorial that shows how to build a C# application that can search the web using Google's Web Service.

On Saturday, July 10th 2004 at 08:49 AM
By Andrew Pociu (View Profile)
*****   (Rated 4.6 with 16 votes)
Contextual Ads
More C# Resources
Advertisement








With the Google Web APIs service, software developers can query more than 4 billion web pages directly from their own computer programs. Google uses the SOAP and WSDL standards so a developer can program in his or her favorite environment - such as Java, Perl, or Visual Studio .NET.
Google Web APIs



In this tutorial we'll make a little application that can search the web with Google. It will use of course a web service provided by Google. More information about it can be found at http://www.google.com/apis/.

Before we start you need to have an account at Google because using that account you can get the license key (don't worry, it's free) that will allow you to do 1000 queries per day. So register at https://www.google.com/accounts/NewAccount and after you confirm using the link in the email they sent you go to http://api.google.com/createkey and you'll get another email from Google containing the key you need.



There's no need to download the project but if you want, go ahead:

 GoogleWS.zip



Now create a new Windows Application project named GoogleWS and add four TextBoxes with the followin names:



txtKey (where you'll enter you license key, you can set the Text property to your license key now so you don't have to enter it every time you run the application)

txtNum (where the number of results will be displayed)

txtSearch (where the string you want to search will be entered)

txtResult (set the Multiline property of this one to True and ScrollBars property to Both because this is where will display the result)



Further add a ComboBox named cmbPage with the property DropDownStyle set to DropDownList and a Button named btnSearch.

Finaly add two CheckBoxes named chkFilter and chkSafeSearch.



With some labels added this is how the form looks like:





Now let's add a WebReference to Google's WebService. Go ahead, right click the project in Solution Explorer and select Add Web Reference. And this is the URL you need to enter, that points to Google's WebService: http://api.google.com/GoogleSearch.wsdl

The connection is added to Solution Explorer, but let's rename it to google:





First let's see the code:




public void search(int start)

{

   // Set the mouse pointer to Busy

   this.Cursor = Cursors.WaitCursor;

   // Clear for any earlier results

   txtResult.Clear();

   // Create new GoogleSearchService

   google.GoogleSearchService GSS = new google.GoogleSearchService();

   // Create new GoogleSearchResult

   google.GoogleSearchResult GSR = GSS.doGoogleSearch(txtKey.Text, txtSearch.Text, start, 10, chkFilter.Checked, "",    chkSafeSearch.Checked, "", "", "");


   // Store the number of total results

   int resNum = GSR.estimatedTotalResultsCount;

   // resNumX will be used for looping

   int resNumX = 0;

   // Show the number of results

   txtNum.Text = resNum.ToString();

   // Loop through all the results

   while(resNum > resNumX)

   {

      // Add them to the combo box

      cmbPage.Items.Add(resNumX.ToString() + " - " + (resNumX+10));

      // Increment with 10 because we display 10 items / page

      resNumX = resNumX + 10;

   }

   // Select the coresponding item

   cmbPage.SelectedIndex = (start / 10);

   // Word suggestion

   string suggested = GSS.doSpellingSuggestion(txtKey.Text, txtSearch.Text);

   // If there is a suggestion

   if(suggested != null)

   {

      // Show it

      txtResult.AppendText("Did you mean: " + suggested + "\r\n\r\n");

   }

   // Loop through the elements

   foreach(google.ResultElement result in GSR.resultElements)

   {

      // Show the title

      txtResult.AppendText(result.title + "\r\n");

      // The URL

      txtResult.AppendText(result.URL + "\r\n");

      // And the summary

      txtResult.AppendText(result.summary + "\r\n");

   }

   // Set the selection start to 0...

   txtResult.SelectionStart = 0;

   // so we can scroll to the top of the textBox

   txtResult.ScrollToCaret();

   // Set the cursor back

   this.Cursor = Cursors.Default;

}

private void btnSearch_Click(object sender, System.EventArgs e)

{

   // Do the search starting from item 0

   search(0);

}


private void cmbPage_SelectedIndexChanged(object sender, System.EventArgs e)

{

   // If the index is changed start from the item

   // equal with the selected item in the combo box


   search((cmbPage.SelectedIndex * 10));

}




The most important method that we used is the following:




doGoogleSearch(string key, string q, int start, int maxResults, bool filter, string restrict, bool safeSearch, string lr, string ie, string oe)



Compile it and give it a try. Don't enter a very common keyword like programming or Microsoft because it will take longer than you think. The name geekpedia isn't so well known , here's the result:







Further you should download the Google Web APIs Developer Kit and check Google Web APIs Reference to add more functionality to the program.
Digg Digg It!     Del.icio.us Del.icio.us     Reddit Reddit     StumbleUpon StumbleIt     Newsvine Newsvine     Furl Furl     BlinkList BlinkList

Rate Rate this tutorial
Comment Current Comments
by Kelvin Y on Wednesday, December 15th 2004 at 08:47 AM

Brilliant example of using a real-world web service. There is a minor bug in the code. There is an event loop caused by cmbPage_SelectedIndexChanged which makes the combo list grow each time a new selection is made. It takes a little long to describe the fix but I can do it if necessary.

by thanh on Saturday, July 9th 2005 at 11:12 PM

Excellent. Thanks for yor sharing

by J.Celmer on Tuesday, March 7th 2006 at 03:05 PM

I've got some problem with this example, namingly the application works very very slowly and eventually an error pops up:
Exception System.ArgumentOutOfRangeException was thrown in debugee:
InvalidArgument=Value of '0' is not valid for 'SelectedIndex'.

set_SelectedIndex()
search() - c:\.......\Project\GoogleWS\GoogleWS\Form1.cs:237,4
btnSearch_Click() - c:\........\Project\GoogleWS\GoogleWS\Form1.cs:266,4
OnClick()
OnClick()
OnMouseUp()
WmMouseUp()
WndProc()
WndProc()
WndProc()
OnMessage()
WndProc()
DebuggableCallback()
System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop()
RunMessageLoopInner()
RunMessageLoop()
Run()
Main() - c:\.........\GoogleWS\GoogleWS\Form1.cs:208,4.

Only from time to time it succeds in finding search results.

by RameshPrasad on Thursday, September 14th 2006 at 02:22 PM

the application works very very slowly and eventually an error like this show

ContextSwithDeadloack was dedected every time

The CLR has been unable to transition from COM context 0x1a09c8 to COM context 0x1a0b38 for 60 seconds. The thread that owns the destination context/apartment is most likely either doing a non pumping

what iam do please give me valueble suggestion

by Umesh on Thursday, May 15th 2008 at 07:56 AM

I Sign-up for an AJAX Search API Key and get the key and try to search with this example but i got error like this "Invalid Key".
Even i tried with 2 keys ( which are generated by 2 different mail Id).

by Umesh on Friday, May 16th 2008 at 12:47 AM

Actually when i generate the API key that time i given my web site name is "www.google.com" . The reason behind this is i want this serial key for windows application (example given on site) .
Then i found it is for web application .I have to give url of my web application in my site text box.
Please advice me if i do any wrong and can any one advice me how will i used the google api for windows application.

by Developer on Friday, September 17th 2010 at 01:09 AM

hello,

First of all many many thanks for this guidance..

I am Dot net Developer and I have to create application which can fetch suggested keywords from google and yahoo engine.

I download your demo but I am not getting key to get result from this example.
http://api.google.com/createkey is not working.. How can I generate key to test this demo? Each time I have to enter key? When i deploy the application in client machine, does used also need any type of key to use google API?

Please reply me as soon as possible because I have to start may project urgently..

Really thanks in advance..

by Russell on Wednesday, February 16th 2011 at 09:32 PM

@Developer, This WSDL Example is obsolete and will no longer be used by Google Services. Try looking at there examples for Google.Gdata.Client.

by love stories on Saturday, August 13th 2011 at 07:25 AM

What a wonderful leather of assemblage Admiring the naming and activity you put into your diary and elaborated substance you substance ! I give marker your diary and bespeak my children canvas up here oft. Thumbs up

by Congestive Heart Failure on Saturday, August 13th 2011 at 04:24 PM

Excavation folks, I approximation you should cerebrate several dynamical a write group, am I fusty? Or at lesser gray the comments. Anyways I sought to say that I likable this displace on Facebook.
http://www.heartattackgo.net/congestive-heart-failure/

by funny life quotes on Monday, August 15th 2011 at 11:39 AM

work in a graveyard shift. I was getting bored at work as no work here at office. So was searching through some blogs and came across your blog, great work man I liked what you wrote Inspirational and very meaningful.
<a href="http://www.Famousfunnylifequotes.com/">funny life quotes</a>">funny life quotes </a>

by short love quotes on Wednesday, August 17th 2011 at 02:10 AM

Wow thanks for such a great article here. I was searching for something like that for quite a long time and at last I have found it here. Thanks for posting it here and keep publishing such nice ones in the future too.

by software review on Saturday, November 5th 2011 at 03:14 AM

I am very glad that I find your regular post here. Which seems to be very important and it made good time pass for me.

by Web design Tucson on Sunday, November 6th 2011 at 10:49 AM

I find this procedure quite impressive, for those who look for creating their own small filter tool to refine queries on Google. I believe this could be really useful for people who write academic work, for instance, because they need to run research on isolated and refined fields. I still think about how this could work for me if I own, let`s say, a small online business. I would still be interested for visitors to use the giant Google in order to find my websites.

by colocation San Diego on Saturday, November 26th 2011 at 04:07 PM

I'm a big fan of web services because they automate things and as a programmer I need to find shortcuts every time so I can deliver the project by its deadline. Definitely something worth looking at.

by magazine subscriptions to Switzerland on Monday, December 12th 2011 at 04:52 AM

thank u for providing me information on List View.
I want to know how i can display data in datalist in Newsletter layout and Thank you so much, this is easy to understand and fun to continue along with. I am a migrating VB.NET/C# Developer looking for an insight into VC .NET. I've found the VC tutorials on many sites to be confusing, and the navigation around the sites to be near impossible to use! Thanks once again.

by hardwood floor installation on Saturday, March 3rd 2012 at 06:26 AM

I'm a big fan of snare services because they automate belongings and as a programmer I necessity to discovery shortcuts every time so I tins deliver the project by its deadline. Definitely something worth observing at.


Comment Comment on this tutorial
Name: Email:
Message:
Comment Related Tutorials
There are no related tutorials.

Comment Related Source Code
There is no related source code.

Jobs C# Job Search
My skills include:
Enter a City:

Select a State:


Advanced Search >>
Sponsors
Discover Geekpedia
Other Resources
Bargain EZ Tech Coupons & Deals