Thursday, October 1, 2009

Google Base API - Insert a Housing Entry via a Batch Feed

I've been looking for a straight forward .Net example on how to upload a "Housing" item entry via a batch in the Google Base API, but to no avail. Mind you this is for Australia, so the required attributes are a bit different for the United States. After talking with someone at Google, we got it sorted out. Here's my example:

using Google.GData.Client;
using Google.GData.GoogleBase;


public static class GoogleBaseFacade
{
private static GBaseService service;

private static void Connect()
{
if (service == null)
{
service = new GBaseService("TEST - Homes for Sale", <google key>);
service.setUserCredentials(<login>, <password>);
service.NewAtomEntry += new FeedParserEventHandler(service_NewAtomEntry);
}
}

static void service_NewAtomEntry(object sender, FeedParserEventArgs e)
{
if (e.Feed != null && e.Feed.Entries != null && e.Feed.Entries.Count > 0)
{
foreach (AtomEntry entry in e.Feed.Entries)
{
if (entry.BatchData != null)
{
Console.WriteLine("New Entry STATUS CODE: " + entry.BatchData.Status.Code.ToString());
}
else if (entry.Id != null && entry.Id.Uri != null)
{

Console.WriteLine("New Entry URI: " + entry.Id.Uri);
}
else
{
Console.WriteLine("New Entry ???");
}
}
}
else
{
Console.WriteLine("No Feed or Entries in feed. Possible single entry");
}
}

public static void AddAHome()
{
Connect();
//create an entry
GBaseEntry entry = new GBaseEntry();
AtomPerson author = new AtomPerson(AtomPersonType.Author,"James Smith");
author.Email="jamessmith@example.com";
entry.Authors.Add(author);
entry.GBaseAttributes.AddTextAttribute("target_country", "AU");
entry.GBaseAttributes.ItemType = "Housing";
entry.GBaseAttributes.AddNumberAttribute("bathrooms", 2);
entry.GBaseAttributes.AddNumberAttribute("bedrooms", 3);
entry.GBaseAttributes.AddTextAttribute("description", "A fantastic underground house.");
entry.Links.Add(new AtomLink("http://www.velociraptorz.org"));
entry.GBaseAttributes.AddTextAttribute("listing_type", "residential for sale");
entry.GBaseAttributes.AddNumberAttribute("price", 1200000);
entry.GBaseAttributes.AddTextAttribute("property_type", "house");
entry.GBaseAttributes.Location = "1 Market St, Sydney, NSW, 2000";
entry.Title.Text = "A safe haven, underground.";
entry.BatchData = new GDataBatchEntryData("blahblah", GDataBatchOperationType.insert);
entry.BatchData.Id = "batch1234";

AtomFeed batchFeed = new AtomFeed(GBaseUriFactory.Default.ItemsFeedUri, service);
batchFeed.Entries.Add(entry);

GBaseFeed returnFeed = service.Batch(batchFeed, GBaseUriFactory.Default.ItemsFeedBatchUri) as GBaseFeed;
}
}


Here are some useful links:


I hope this helps someone.

No comments: