Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

A google search application using Gtk#

0.00/5 (No votes)
14 Jan 2005 1  
An application (based on Gtk#) which uses the google web service to search the internet.

Sample Image - googleSearch.jpg

Introduction

GTK (GIMP Toolkit) is a library for creating graphical user interfaces. It is licensed using the LGPL license, so you can develop open software, free software, or even commercial non-free software using GTK without having to spend anything for licenses or royalties. Gtk# is a binding for mono to this great toolkit, that is usable from any Mono language including MonoBasic and C#. There is also a binding for .NET Framework v1.1 on Windows.

Gtk can be installed for both Windows and Linux, though the Linux version is a little faster and more stable as compared to the Windows version. I am going to show how to create a cross-platform application using .NET and Gtk#. The development environment I describe here is based on windows. However you can also use Linux as your development environment.

The application will perform an internet search using the Google webservice. Firstly, you need to have a google developer account. If you don�t have an account you can create one at https://www.google.com/accounts/NewAccount

Once your account is created you�ll receive a licence key from google which is 32 byte alphanumeric string e.g. 0AdaQ5lQFHJmWhI5UACEjtgIcwRezTJ5. Keep this safe since this is required for every web service call you make to Google web service.

Development Environment (Windows)

The development environment on windows for Gtk# apps consists of the following:

  1. Visual Studio .NET 2003 (IDE)
  2. Gtk# (cross platform UI toolkit)
  3. Glade (UI designer)

(If you don�t have Visual Studio you can also use SharpDevelop. You can either use .NET Framework v1.1 for development or configure your Visual Studio to use Mono.)

The executables produced can be run directly on Linux workstations with Mono and Gtk# installed. They can also be run on any windows workstation which has .NET Framework 1.1 (or Mono) and Gtk# installed.

Note: You need to install Glade only on the development machines.

Setting up the development environment (Windows)

  1. Installing Gtk#

    The Gtk# homepage http://gtk-sharp.sourceforge.net/ contains a link to a win32 installer. Download and install. There are 2 versions available on the website � v1.0.2.4 and v1.9.1.0. I have tried out v1.0.2.4 and it works perfectly though the latter version should also work.
  2. Installing Glade

    Download and install Glade from http://gladewin32.sourceforge.net/. You also have to download and install the Gtk+ runtime from the same website.

Development Environment (Linux)


The development environment on windows for Gtk# apps consists of the following:

  1. MonoDevelop (IDE)
  2. Gtk# (cross platform UI toolkit)
  3. Glade (UI designer)

The executables produced can be run directly on Linux workstations with Mono and Gtk# installed. They can also be run on any windows workstation which has .NET Framework 1.1 (or Mono) and Gtk# installed.

Note: You need to install Glade only on the development machines.

Setting up the development environment (Linux)

  1. Installing MonoDevelop

    Refer to its website http://www.monodevelop.com/ for installation instructions.
  2. Installing Gtk#

    The instructions can vary depending on what version of Linux you run. Refer to http://gtk-sharp.sourceforge.net/ for instructions.
  3. Installing Glade

    Refer to http://glade.gnome.org/ for latest version and installation instructions.

Overview

Now that you have your development platform setup let me explain the various components and how they interact with each other. Glade is a click-n-drag UI designer. It is used to create the user interface for your application. Once the user interface is complete it saves the UI as an XML file. This xml file is used by the .NET(or Mono) application to build user interface at runtime. The application uses the Gtk# and Glade# library (Glade# is packaged with the Gtk#) to read the XML and create a UI.

Building the interface

The first step is to build the user interface. Open Glade. If you can�t find it on your desktop, it should be present in C:\Program Files\Gtk\bin.

You should see 3 windows open up.

Glade

Click on the window icon in the Palette window. A window is created.

Glade window

Change the window properties using the Properties dialog. Set Window name to mainWindow and Title to �Gtk# - Google Search�. You should also set the default width and height.

Glade Properties

Next click the vertical box button ( vertical) and click in the window. Select 2 rows when prompted.

Glade

Your window will now be divided into 2 parts.

Glade

To make space to add a textbox and buttons, click on the horizontal box (Horizontal ) and click on the top half of the vertical box you created earlier. Choose 3 columns when prompted.

Sample screenshot

In the three columns of the top half of the window, add a text entry and 2 buttons. After you do so your interface should like this.

Sample screenshot

Now right click on the top half of the window and choose hbox->select. Change its Packing property so that Expand and Fill are �No�.

Sample screenshot

Click on button1 in the window and change its Name property to btnSearch, Label to Search and Icon property to Find.

Sample screenshot

Click on button2 in the window and change its Name property to btnClear, Label to Clear and Icon property to Clear.

Sample screenshot

Now your window should look like this.

Sample screenshot

Now all you need to do is to add in a search results box. Add a text view component to the lower half of the window. At this point the interface should look like this.

Sample screenshot

Now save the interface

Sample screenshot

In the save options, you can ignore the �C Options� tab and the �LibGlade Options� tab. That should complete your UI design. Now you�ll go on to linking up the code with the user interface.

Coding

Fire up your visual studio 2003 and create a new empty C# project. Call it googleSearch.

Add Reference to the following assemblies: atk-sharp, gtk-sharp, gdk-sharp, glade-sharp, glib-sharp. In the project properties set the Output Type to �Windows Application�


Add the googleSearch.glade to the project. Right-click on the filename in the solution explorer and change the Build Action property to �Embedded Resource�. This ensures that the file is embedded inside the executable produced by compiling the project.

Lets add a web reference to the Google Web Service. Right click on References in the solution explorer and choose to add a new web reference. Type the url http://api.google.com/GoogleSearch.wsdl and press Go. You should see the following screen.

Adding web sreference in Visual Studio

Press Add Reference. This creates the classes necessary to connect to the google web service. (If you are not using Visual Studio, you can do the same by using the wsdl.exe command line program which is a part of the .NET Framework SDK and can be found at C:\Program Files\Microsoft.NET\SDK\v1.1\Bin.)

Add a new class called GtkApp.cs.

using System;
using Gtk;
using Glade;
using googleSearch.com.google.api;

namespace googleSearch
{
 /// <summary>

 /// Summary description for GtkApp.

 /// </summary>

 public class GtkApp
 {
  
  [Widget]Window mainWindow;
  [Widget]Button btnSearch;
  [Widget]Button btnClear;
  [Widget]Entry entry1;
  [Widget]TextView textview1;

  /* Main Function */
  public static void Main (string[] args)
  {
   new GtkApp (args);
  }


  public GtkApp(string []args)
  {
   Application.Init();

   Glade.XML gxml = new Glade.XML (null, "googleSearch.googlesearch.glade", 
                                  "mainWindow", null);
   gxml.Autoconnect (this);
   mainWindow.DeleteEvent+=new DeleteEventHandler(mainWindow_DeleteEvent);
   btnSearch.Clicked+=new EventHandler(btnSearch_Clicked);
   btnClear.Clicked+=new EventHandler(btnClear_Clicked);
   Application.Run();
  }

  private void mainWindow_DeleteEvent(object o, DeleteEventArgs args)
  {
   Application.Quit ();
   args.RetVal = true;
  }

  private void btnSearch_Clicked(object sender, EventArgs e)
  {
   try
   {
    textview1.Buffer.Text="";

    //do search

    GoogleSearchService svc=new GoogleSearchService();
    GoogleSearchResult result
          =svc.doGoogleSearch("FEkTsl8kwgQtrQIeGHJDSELrTtjNcp1eC",
                               entry1.Text,0,10,true,"",true,"","","");
   
    foreach(ResultElement re in result.resultElements)
    {
     textview1.Buffer.Text+="Title: "+re.title+"\r\n";
     textview1.Buffer.Text+="Summary: "+re.summary+"\r\n";
     textview1.Buffer.Text+="URL: "+re.URL+"\r\n";
     textview1.Buffer.Text+="==========================\r\n\r\n";
    }

   }
   catch(Exception ex)
   {
    Gtk.MessageDialog md=new MessageDialog(mainWindow,Gtk.DialogFlags.Modal,
                        Gtk.MessageType.Error,Gtk.ButtonsType.Ok,ex.Message);
    md.Show();
   }
  }

  private void btnClear_Clicked(object sender, EventArgs e)
  {
   textview1.Buffer.Text="";
   entry1.Text="";
  }

  
 }
}

Now build and start the project. You should see a window that looks like the following.

Sample screenshot

Type some terms in the text box and press search. You�ll see search results, which are returned by Google.

I�ll go through some of the more important parts of the code now.

[Widget]Window mainWindow;

This line defines mainWindow to be of type Gtk.Window. The name must match the name defined in Glade. The same holds true for the remaining declarations.

Application.Init();

This line initializes the Gtk Application.

Glade.XML gxml = new Glade.XML (null, "googleSearch.googlesearch.glade", 
                               "mainWindow", null);
gxml.Autoconnect (this);

This loads the XML file googlesearch.glade and defines mainWindow to be the root element. The Autoconnect call links up widget names with the declarations made previously. E.g. The variable mainWindow defined in the class declaration is linked to the mainWindow defined in the googlesearch.glade file.

mainWindow.DeleteEvent+=new DeleteEventHandler(mainWindow_DeleteEvent);
btnSearch.Clicked+=new EventHandler(btnSearch_Clicked);
btnClear.Clicked+=new EventHandler(btnClear_Clicked);

These lines define the event handlers for various events. It is not necessary to define the events manually. You can actually define the event handlers using Glade. In that case, when Autoconnect call is made it�ll automatically link up the events to the event handlers.

Application.Run();

This starts the Gtk Application.

GoogleSearchResult result
      = svc.doGoogleSearch("FEkTsl8kwgQtrQIeGHJDSELrTtjNcp1eC",
                          entry1.Text,0,10,true,"",true,"","","");

This makes a web service call to the Google web service. The result contains the search results. The first parameter is your License key which you should have obtained from Google as described earlier in this article.

To run this program in Linux, simply recompile the project as Release, then copy the googleSearch.exe file found in the bin\Release folder to the Linux machine. On the shell prompt type

# mono googleSearch.exe

This should start the program. Of course, you must have mono and gtk-sharp installed on the Linux machine.

Some tips for cross platform development

  1. There are some Namespaces that should be avoided as far as possible because they are not completely supported by Mono as yet.

    Microsoft.Win32
    System.Windows.Forms
    System.Messaging
  2. Use relative paths when naming files. The file C:\Program Files\yourapplication does not exist on Linux, and /usr/lib/ isn't available under Windows. Also remember that Linux filenames are case-sensitive unlike windows.
  3. Avoid platform-specific resources like the Windows registry (Microsft.Win32.Registry).
  4. Use Gtk# for building applications. Gtk# for Windows is better than System.Windows.Forms for Linux.
  5. Only use Platform Invoke (P/Invoke) if you really need it. If possible, use a library that is available on UNIX and Windows.
  6. Mono does not support incremental debug builds, which are used extensively by Visual Studio for faster compilation. When deploying files created in Visual Studio to Linux do a Rebuild as Release.
  7. Avoid using Visual Basic .NET since support for it in Mono is still beta.

Conclusion

This hopefully introduces you to the basics of how to use Gtk# in .NET. For more details, API listings etc take a look at the references section. The Gtk# API is very close to the Gtk API since its mainly a wrapper around Gtk. Hence, you can use the Gtk API itself as a reference. For more tutorials on using Gtk# refer to the Mono Handbook.

References

  1. Mono Handbook http://monohandbook.monoforge.com/monkeyguide/index.html
  2. MonoWiki http://www.nullenvoid.com/mono/wiki/
  3. Glade# for Rapid Development http://primates.ximian.com/~edasque/projects/Tutorial/glade2.html
  4. Glade Tutorial http://www.kplug.org/glade_tutorial/glade2_tutorial/glade2_introduction.html
  5. GTK Tutorial http://www.gtk.org/tutorial/

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here