RSS

Google Book Search in C#: A step by step walk-through tutorial

18 Dec

Several years earlier, I wrote a python script to perform ISBN book search: given the isbn number, the python script simply dumps the books title, publisher and author information, which are then used to rename the pdf that is downloaded into a more informational file name:

123456789a.pdf –> Elsevier_2010_A simple and effective geometric representation for irregular porous structure modeling.pdf

It is a handy script but unfortunately I lost it after a hard disk failure!

And then I decide to recover this from my brain, but I would like to implement it in another my favorite language, C#.

image

Source code of this project can be downloaded from GitHub here.

Google Book Search API turns out to be the library that I found quite appealing. Yes, unfortunately again, I found there lacks a simple walk-through tutorial that can direct me step-by-step. That motivated me to write a blog tutorial for this!

To get started, follow below steps:

  • Create a C# project, either a console or GUI (e.g. Winform or WPF) application will do;
  • Create a class in the project, let’s call it BookSearch class
  • Add a static method, as shown below:

           public static async Task<Volume> SearchISBN(string isbn)
        {
            Console.WriteLine(“Executing a book search request…”);
            var result = await service.Volumes.List(isbn).ExecuteAsync();
            if (result != null && result.Items!=null)
            {
                var item = result.Items.FirstOrDefault();
                return item;
            }
            return null;
        }

  • To make the above code compile, we need a service object:
     public static BooksService service = new BooksService(
            new BaseClientService.Initializer
     {
            ApplicationName = "ISBNBookSearch",
            ApiKey = "abcdefghijklmnopqrstuvwxyz",
     });


where the string “abcdefghijklmnopqrstuvwxyz” is the api key Google gives you, shall show you later how to get this! At the moment, let’s focus on the main logic!

All right, everything seems trivial, but this won’t compile at all. To get this code compile, do the following:

  • Using Nuget to install the Google Books API .net lib:

PM > Install-Package Google.Apis.Books.v1

image

  • An alternative solution of not using the Nuget Package console is: Right click on the reference folder in the project, and click “Manage Nuget Packages” menu item, and then search “Google Books API” in the popup dialog

image

image

  • The Google Books API and its dependent library will be installed.
  • Build the project, everything should be fine.

To test the code, I created a unit testing project, and added below tests:

[TestClass]
public class BookSearchTest
{
    [TestMethod]
    public void TestIsbnSearch()
    {
        string isbn = "0071807993";
        var output = BookSearch.SearchISBN(isbn);
         
        Assert.AreEqual(output.Result != null, true);

        var result = output.Result;
        Trace.WriteLine("\nBook Name: " + result.VolumeInfo.Title);
        Trace.WriteLine("Author: " + result.VolumeInfo.Authors.FirstOrDefault());
        Trace.WriteLine("Publisher: " + result.VolumeInfo.Publisher);
    }
}

 

Success!

image


Almost done! But wait, where can I get the API key? You might be interested in this article to find how. But to make this post self-contained, you might wish to do as following:

  • Login with you Google account
  • To acquire an API key, visit the APIs Console.
    • In the Services pane, activate the Books API;

image

    • Then go to the Credentials pane. Click the “Create new Key” button, and then you will get an API key such as “abcdefghijklmnopqrstuvwxyz”  

image

    Once you have this api key, the above code will run without problem!
    You can get the example code of this project from GitHub here. Happy coding!

Advertisements
 
14 Comments

Posted by on December 18, 2014 in Dotnet/C#, Java, Programming

 

Tags: , , , , , , , , , , , ,

14 responses to “Google Book Search in C#: A step by step walk-through tutorial

  1. Remco

    June 16, 2015 at 8:01 pm

    Hello Xinyustudio, I’m trying to turn this into a simple windows form application however without succes. Your tutorial mentions that your code should work in a windows form application however I can’t seem to get it to work. I’ve tested your code as a console application, which works perfectly. I can’t seem to find a PM option on this website, hence this (Somewhat long) comment. I’ve replaced my API key with “MyAPIKey” for obvious reasons.

    I hope you can give me some pointers! The code compiles without error and from what I’ve been able to determine it messes up when it tries to fill the variable ‘result’ in the SearchISBN function.

    Here’s my form1.cs:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using Google.Apis.Auth.OAuth2;
    using Google.Apis.Auth.OAuth2.Flows;
    using Google.Apis.Books.v1;
    using Google.Apis.Books.v1.Data;
    using Google.Apis.Services;
    using Google.Apis.Util.Store;

    namespace BookSearchApp3
    {
    public partial class Form1 : Form
    {
    public Form1()
    {
    InitializeComponent();
    }

    private static string API_KEY = “MyAPIKey”;

    public static BooksService service = new BooksService(new BaseClientService.Initializer
    {
    ApplicationName = “ISBNBookSearch”,
    ApiKey = API_KEY,
    });

    public static async Task SearchISBN(string isbn)
    {
    MessageBox.Show(“Executing a book search request for ISBN: …”);
    var result = await service.Volumes.List(isbn).ExecuteAsync();

    if (result != null && result.Items != null)
    {
    var item = result.Items.FirstOrDefault();
    return item;
    }
    return null;
    }

    private void CheckISBN_Click_1(object sender, EventArgs e)
    {
    string isbn = textBox1.Text;
    var output = SearchISBN(isbn);
    var result = output.Result;

    MessageBox.Show(result.VolumeInfo.Title);
    MessageBox.Show(result.VolumeInfo.Authors.FirstOrDefault());
    MessageBox.Show(result.VolumeInfo.Publisher);
    }
    }
    }

     
  2. xinyustudio

    June 17, 2015 at 9:10 am

    “I can’t seem to get it to work.” what is the error?

     
  3. Remco

    June 17, 2015 at 3:48 pm

    Ah shit, my bad, I run my form, fill out the ISBN, hit the check button and the “Executing a book search request” messagebox pops up, I hit OK and the program hangs.

    When I run the form the following things of note appear in my console:

    The thread 0xe6c has exited with code 259 (0x103).
    The thread 0xfc4 has exited with code 259 (0x103).

    After I fill in the ISBN and hit check the messagebox pops up, I hit OK and the following things of note appear in my console:

    The thread 0xed4 has exited with code 259 (0x103).
    The thread 0x13c0 has exited with code 259 (0x103).
    The thread 0x1094 has exited with code 259 (0x103).
    The thread 0x1484 has exited with code 259 (0x103).

    After which the program hangs.

    I just noticed that in my comment the Volume part of the SearchISBN method name was omitted, it’s there in the actual code though.

    The result variable in the SearchISBN method seems to stay null when I try debugging, However it’s neatly filled when running your code as a console application.

    Thanks for taking a look, I’m still trying to get the hang of this whole C# thing so any help is definitely appreciated!

     
  4. Amit

    December 12, 2015 at 8:25 pm

    Thanks for the wonderful article

     
  5. Lyon

    February 9, 2016 at 5:34 pm

    i have the same problem as Remco, if someone could help us please

     
  6. Lyon

    February 9, 2016 at 5:35 pm

    I have the same problem as Remco, someone could help us please

     
  7. siddharth

    February 9, 2016 at 9:39 pm

    same problem here..trying to make it work for c# windows form application

     
  8. makaveli75

    March 5, 2016 at 10:18 pm

    up

     
  9. Lyon

    March 29, 2016 at 4:48 pm

    nobody for help ?

     
  10. Lyon

    March 31, 2016 at 3:14 pm

    up

     
  11. Ivan

    May 16, 2016 at 3:27 am

    I found the same error than @Remco. I was able to solve it adding “await” here:

    var output = await SearchISBN(isbn); // inside private void CheckISBN_Click_1 (@Remco’s code)

    The task returns the requested data at the first try. However, I can see that the application continues creating/closing threads.

     
  12. Ivan

    May 16, 2016 at 4:30 am

    Just added “async” and “await”:

    private async void CheckISBN_Click_1(object sender, EventArgs e)
    {
    string isbn = textBox1.Text;
    var output = await SearchISBN(isbn);
    var result = output.Result;

    MessageBox.Show(result.VolumeInfo.Title);
    MessageBox.Show(result.VolumeInfo.Authors.FirstOrDefault());
    MessageBox.Show(result.VolumeInfo.Publisher);
    }
    }
    }

     

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: