Google Desktop provides a couple of ways to query its index: using the local HTTP server or using the COM Query API . In this post the COM API will be used from C#.
The first step to start working with this API in .NET is to import the typelib
C:\temp\tst>tlbimp <google-desktop-path>\GoogleDesktopAPI2.dll
This will generate the file GoogleDesktopAPILib.dll.
The next thing you need to do is to register the application that will be using the COM API. Here's the code to register the application (taken from the JScript examples ):
using GoogleDesktopAPILib;
...
static int Register() {
int cookie;
object[] description = new object[]{
"Title",
" tests",
"Description",
"Simple tests",
"Icon",
"My Icon@1"
};
string myGuid = "{5323E036-345C-4323-548D-32AA55603215}";
GoogleDesktopRegistrar registar
= new GoogleDesktopRegistrar();
registar.StartComponentRegistration(myGuid,description);
object regObjObj =
registar.GetRegistrationInterface(
"GoogleDesktop.QueryRegistration");
IGoogleDesktopRegisterQueryPlugin q =
regObjObj as IGoogleDesktopRegisterQueryPlugin;
if (q == null) {
throw new Exception("Registration problem");
}
cookie = q.RegisterPlugin(myGuid,true);
registar.FinishComponentRegistration();
return cookie;
}
Registration needs to be executed just once. The returned cookie value could be stored somewhere and reused when the application is executed. For example the JScript demos in the GD SDK use the registry to store the cookie. In this demo I'm going to use a text file to store the cookie.
static int GetRegistrationCookie() {
int cookie;
FileInfo cookieFile = new FileInfo(CookieFileName);
if (cookieFile.Exists)
{
StreamReader reader =
new StreamReader(cookieFile.FullName);
string line = reader.ReadLine();
cookie = int.Parse(line.Trim());
reader.Close();
}
else
{
cookie = Register();
StreamWriter writer =
new StreamWriter(CookieFileName);
writer.WriteLine( cookie.ToString() );
writer.Close();
}
return cookie;
}
Now that we have the registration cookie we can call the Query API . This API is accessed with the GoogleDesktopQueryAPI class. This class has a Query method which receives the registration cookie, a string with the query, and some options. Here's the source for our Main method of a program which receives a query from the command line and prints the location of the matching resources:
public static void Main(string[] args)
{
if (args.Length == 1 && args[0] == "-unregister") {
UnRegister();
} else {
int cookie = GetRegistrationCookie();
string queryString = string.Join(" ",args);
GoogleDesktopQueryAPI queryAPI =
new GoogleDesktopQueryAPI();
IGoogleDesktopQueryResultSet rs =
queryAPI.Query(cookie,queryString,null,null);
IGoogleDesktopQueryResultItem2 i;
while ((i = (IGoogleDesktopQueryResultItem2)rs.Next()) != null) {
Console.WriteLine(i.GetProperty("uri"));
}
}
}
There's a lot of properties that can be extracted from a result item depending on its schema, for example if the result is a mail message.
Code for this post can be found here.