Click here to Skip to main content
15,883,883 members
Articles / Programming Languages / C#
Article

Exploiting the Blogger Atom API

Rate me:
Please Sign up or sign in to vote.
4.54/5 (20 votes)
11 Dec 20057 min read 116.4K   560   34   22
A .NET based API for interacting with Blogger.com.

Image 1

Contents

Introduction

I was looking for a Blogger.com client for my Pocket PC, but unfortunately, I was not satisfied with any of the applications that I had found. So, I decided to develop one myself. I started by developing an independent .NET API for interacting with Blogger.com. This is presented here. This component, which I have named NBlog, allows any .NET application to simply perform different operations against Blogger.com without any knowledge of the underlying communication protocols.

NBlog uses the new Blogger Atom API as the main communication protocol. However, being designed with extensibility in mind, it allows for implementations of any other Blogger-supported protocol to be added. These new implementations can then be plugged into the existing applications by using a simple configuration setting.

To show how NBlog can be used within an application, I've also developed a simple Windows Forms Blogger client. The image at the top is a screenshot from this application.

Overview of the AtomAPI

As mentioned above, NBlog uses the Blogger Atom API as the main protocol for communication with the Blogger. The Blogger Atom API is based on the AtomAPI, which is an application level protocol for publishing and editing web resources. The protocol at its core is the HTTP transport of XML payloads. In this protocol different operations are specified with different HTTP methods (GET, PUT, POST, ...). The input data for each operation is provided as Atom formatted XML in the HTTP request body, and the output data is returned as Atom formatted XML data in the HTTP response body.

For example, the following AtomAPI request can be used for receiving the list of a user's blogs from the Blogger:

GET /atom HTTP/1.1
Host: www.blogger.com
Authorization: BASIC b9Oj4vdRldmVqGFzc5dvcmQyZVFdcGF=

which will return:

XML
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<feed xmlns="http://purl.org/atom/ns#">

    <userid xmlns="http://www.blogger.com/atom/ns#">2114778</userid>

    <link href="https://www.blogger.com/atom/29497767" rel="service.post"
        title="A Sample Blog" type="application/atom+xml"/>

    <link href="https://www.blogger.com/atom/29497767" rel="service.feed"
        title="A Sample Blog" type="application/atom+xml"/>
    ...
</feed>

To know more about the Blogger Atom API and the AtomAPI visit the following sites:

NBlog's core design

In the design of NBlog, I mainly focused on achieving the following:

  • First, to make NBlog extensible by designing an interface that is independent of the technology and protocol used for interacting with the Blogger.
  • And second, to utilize minimum amount of AtomAPI implementation, rather than designing a complete AtomAPI library.

The advantage of having a protocol independent interface is that the applications using it can be seamlessly configured to use different implementations of any other Blogger-supported technology.

The following diagram shows the main classes and interfaces that build up NBlog's core:

Image 2

The "IBloggerProvider" interface

The IBloggerProvider interface is the heart of NBlog's core design. It is the interface that is exposed to the client applications, and it's also the main extension point of the NBlog. This interface contains methods for performing different operations against the Blogger. I've tried to cover most of the Blogger operations in the interface, although some of these operations are not supported by some or any of the Blogger APIs, and are only included for future developments.

The following code shows the definition of this interface:

C#
public interface IBloggerProvider
{
    ICredentials Credentials {get;set;}
    IWebProxy Proxy {get;set;}

    UserProfile GetUserProfile();
    void UpdateUserProfile(UserProfile userProfile);

    BlogCollection GetUserBlogs();
    Blog GetBlog(string blogUri);
    void UpdateBlog(Blog blog);

    Post NewPost();
    PostCollection GetBlogPosts(string blogUri);
    Post GetPost(string postUri);
    void CreatePost(string blogUri, Post post);
    void UpdatePost(Post post);
    void DeletePost(string postUri);

    Comment NewComment();
    CommentCollection GetPostComments(string postUri);
    void CreateComment(string postUri, Comment comment);
    void UpdateComment(Comment comment);
    void DeleteComment(string commentUri);
}

The "ProviderFactory" class

The ProviderFactory class provides a factory which enables the creation of IBloggerProvider instances without specifying a concrete implementation. The GetProvider method of this class will use the application configuration data to create, initialize and return the right implementation of the IBloggerProvider at runtime.

The following code shows the GetProvider method of this class:

C#
public class ProviderFactory
{
    public static IBloggerProvider GetProvider()
    {
        // Load provider from config. or use the default provider

        IBloggerProvider provider = LoadProvider();

        if (provider == null)
            provider = new NBlog.Atom.AtomProvider();

        // Setup and return provider

        provider.Credentials = LoadCredentials();
        provider.Proxy = LoadProxy();

        return provider;
    }
    ...
}

The GetProvider method will load and instantiate the configured provider implementation using System.Reflection; or it will use the default provider type if no provider is specified in the configuration. This method will also initialize the Credentials and Proxy properties of the provider based on the settings provided in the application configuration.

The following configuration settings can be specified in the App.config or Web.config files:

XML
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <appSettings>
        <add key="providerSettings"
           value="assembly file name, fully-qualified type-name" />
        <add key="credentials"
           value="blogger username, blogger password" />
        <add key="proxySettings"
           value="address(ip), port, username, password" />
    </appSettings>
</configuration>

Entity classes

These classes represent the entities involved in the Blogger. The Blog and the Post classes are the most essential. The Comment and UserProfile are currently unused, as they are not involved in any of the supported operations. The entities defined in the NBlog's core don't contain any protocol specific logic, and are defined as abstract. Each implementation must extend these classes, and add any protocol-specific logic if necessary. For example, the AtomAPI implementation adds the GetXml and SetXml methods by extending the core entity classes.

There are also some corresponding collection classes for some of the entities, which facilitate the task of handling groups of entities. These collection classes are defined by extending .NET Framework's CollectionBase class, based on the .NET Framework documentation guidelines:

Image 3

The AtomAPI implementation

The current version of NBlog provides an AtomAPI-based implementation of the IBloggerProvider interface. This implementation exploits the most recent and recommended Blogger-supported protocol, which is the "Blogger Atom API". The following diagram demonstrates the classes involved in this implementation and their relation to the core NBlog types:

Image 4

The "AtomProvider" class

The AtomProvider class is at the center of our AtomAPI-based implementation. It implements the IBloggerProvider interface defined by the NBlog's core, as well as the HTTP-based protocol defined by the Blogger and AtomAPI. As mentioned before, the AtomProvider implements only those operations from IBloggerProvider that are supported by the Blogger Atom API. All other operations will throw a NotSupportedException if called at run-time.

As noted earlier, the AtomAPI uses HTTP as its transport protocol, and XML as its data format. As a result, implementing the protocol involves handling HTTP requests and responses, as well as converting data to and from XML. The AtomProvider class takes care of creating and sending the right HTTP request, and retrieving results from the response. But the task of converting data to and from XML is done by the Atom version of the entities and the AtomConverter class.

The "IAtomEntity" interface

As mentioned above, the core NBlog entities are defined as abstract. Therefore, different implementations must extend these entities, and optionally add some protocol specific logic to them. In the AtomAPI implementation, the extended versions of the entities implement the IAtomEntity interface. The IAtomEntity interface defines the contract that's required for an entity to be supported by the AtomAPI implementation:

C#
public interface IAtomEntity
{
    string GetXml();
    void SetXml(XmlNode xmlNode);
}

As you can see, IAtomEntity contains two methods named GetXml and SetXml. These methods generate the XML representation of the entity and initialize the entity for the XML representation respectively.

The "AtomConverter" class

The AtomConverter class is an XML conversion utility, used by the AtomProvider class. It contains any data conversion logic that's not included in the Atom version of the entities.

Using the code

As mentioned in the introduction, there is a sample Blogger client provided as the "WinClient" project in the solution. Although this sample can be a good example of using NBlog in a real application, I've provided a simpler and a more readable sample code below to show a few steps in using the component:

C#
using System;
using System.Collections;
using System.Net;

namespace NBlog.Test
{
    class MainClass
    {
        [STAThread]
        static void Main(string[] args)
        {
            IBloggerProvider provider = ProviderFactory.GetProvider();

            provider.Credentials = new NetworkCredential("user", "pass");

            BlogCollection blogs = provider.GetUserBlogs();

            foreach (Blog b in blogs)
            {
                PostCollection posts = provider.GetBlogPosts(b.Uri);

                Console.WriteLine("{0}: {1} post(s)\n",
                    b.Title, posts.Count);

                foreach (Post p in posts)
                {
                    Console.WriteLine("\t{0} [by {1} @{2}]",
                        p.Title, p.Author, p.CreatedDate);

                    Console.WriteLine("\t{0}\n", p.Content);
                }
            }

            Console.ReadLine();
        }
    }
}

The code simply dumps the recent posts from all blogs of the specified user.

The first step is to get an instance of the IBloggerProvider interface. This task is done by using the ProviderFactory class, rather than directly instantiating a concrete implementation:

C#
IBloggerProvider provider = ProviderFactory.GetProvider();

The ProviderFactory will return an instance of the configured provider, if any; otherwise, it will return an instance of the AtomProvider class. The ProviderFactory will also set the credential and proxy settings of the provider based on the application configuration.

Next, the Credentials must be set on the provider (this will override any credentials specified in the application configuration):

C#
provider.Credentials = new NetworkCredential("user", "pass");

The following code will receive a list of the user's blogs:

C#
BlogCollection blogs = provider.GetUserBlogs();

A foreach statement can be used for going through all the blogs:

C#
foreach (Blog b in blogs)
{
    ...
}

In the body of the foreach statement, the following code is used for receiving the recent posts of each blog:

C#
PostCollection posts = provider.GetBlogPosts(b.Uri);

Finally, the following code will dump each blog's content to the console:

C#
Console.WriteLine("{0}: {1} post(s)\n", b.Title, posts.Count);

foreach (Post p in posts)
{
    Console.WriteLine("\t{0} [by {1} @{2}]",
            p.Title, p.Author, p.CreatedDate);

    Console.WriteLine("\t{0}\n", p.Content);
}

There's one more important task which is not covered in the previous sample, and that's creating a new post. The following code shows the proper way of creating a new post:

C#
Post newPost = provider.NewPost();

newPost.Title = "Sample Post";
newPost.Content = "...";

provider.CreatePost(blogUri, newPost);

Summary

As mentioned earlier, the main motivation for developing NBlog was to create a Blogger API that can be used in a Pocket PC Blogger client. But I believe, NBlog can be quite useful as a standalone component, and it's probably worth presenting here. Hopefully, I'll be able to develop the Pocket PC client very soon, and post it here as well.

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


Written By
Web Developer
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionCould it add label? Pin
Simon.P.G.22-May-12 17:15
Simon.P.G.22-May-12 17:15 
QuestionBlogger API Pin
pedro_66624-Mar-10 5:45
professionalpedro_66624-Mar-10 5:45 
GeneralBlogger api Pin
pedro_66624-Mar-10 5:44
professionalpedro_66624-Mar-10 5:44 
QuestionGoogle got Blogger API blocked? Pin
tech.U10-Sep-08 18:11
tech.U10-Sep-08 18:11 
Generaldoesnt log in Pin
lol187817-May-07 6:04
lol187817-May-07 6:04 
the sample doesnt seem to log in
AnswerRe: doesnt log in Pin
Ali Shojaeddini17-May-07 12:39
Ali Shojaeddini17-May-07 12:39 
Generalerror .... Pin
hung71429-Aug-06 18:36
hung71429-Aug-06 18:36 
AnswerRe: error .... Pin
Ali Shojaeddini30-Aug-06 10:31
Ali Shojaeddini30-Aug-06 10:31 
GeneralRe: error .... Pin
Mohamed Elzahaby10-Sep-06 19:59
Mohamed Elzahaby10-Sep-06 19:59 
Generaldomain authentication for proxy Pin
BlackTigerX19-Apr-06 9:32
BlackTigerX19-Apr-06 9:32 
GeneralRe: domain authentication for proxy Pin
Ali Shojaeddini23-Apr-06 6:06
Ali Shojaeddini23-Apr-06 6:06 
General[Message Deleted] Pin
Richard DeYoung11-Mar-06 22:05
Richard DeYoung11-Mar-06 22:05 
GeneralRe: AtomProvider has bug in CreatePost Pin
Ali Shojaeddini13-Mar-06 9:50
Ali Shojaeddini13-Mar-06 9:50 
QuestionExcellent Pin
DrHodge24-Jan-06 10:39
DrHodge24-Jan-06 10:39 
AnswerRe: Excellent Pin
Ali Shojaeddini27-Jan-06 11:01
Ali Shojaeddini27-Jan-06 11:01 
QuestionProblems with posting Posts Pin
John N7-Dec-05 13:48
John N7-Dec-05 13:48 
AnswerRe: Problems with posting Posts Pin
Ali Shojaeddini8-Dec-05 8:29
Ali Shojaeddini8-Dec-05 8:29 
GeneralThanks! Pin
John N8-Dec-05 11:19
John N8-Dec-05 11:19 
GeneralCongratulations! Pin
Narges Zebarjad3-Dec-05 1:15
Narges Zebarjad3-Dec-05 1:15 
GeneralGreat article! Pin
rht3411-Dec-05 10:20
rht3411-Dec-05 10:20 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.