Thursday, February 18, 2010

How to add a new Blogger post with labels from C#

First download and install Google API from here:
http://code.google.com/p/google-gdata/downloads/list

Add a reference to "Google Data API Core Library",
and use the following function:


public static bool AddPost(string title, string bodyHTML, string[] labels)
{
    Service service = new Service("blogger", "<program name>");
    service.Credentials = new GDataCredentials("<username>", "<password>");
    AtomEntry newPost = new AtomEntry();
    newPost.Title.Text = title;
    newPost.Content = new AtomContent();
    newPost.Content.Content = bodyHTML;
    newPost.Content.Type = "html";
    foreach (string label in labels)
    {
        AtomCategory cat = new AtomCategory();
        cat.Scheme = new Uri("http://www.blogger.com/atom/ns#");
        cat.Term = label;
        newPost.Categories.Add(cat);
    }
    AtomEntry response = null;
    try
    {
        response = service.Insert(new Uri("<uri>"), newPost);
    }
    catch (GDataRequestException exception)
    {
        if (exception.ResponseString == "Blog has exceeded rate limit or otherwise requires word verification for new posts")
        {
            return false;
        }
        else
        {
            throw exception;
        }
    }
    if (response == null)
    {
        throw new Exception("Something went wrong");
    }
    return true;
}

Note what you need to replace:
Also note the marked yellow line. It took me some nasty googling time to find it. You must put it for the labels to work.

8 comments:

  1. Its not working for me :S In try{} something goes wrong but the code in catch not running, and lots of stuff will be posted, or nothing... Please help!

    ReplyDelete
    Replies
    1. response = service.Insert(new Uri("http://www.blogger.com/feeds/" + BLOG_ID + "/posts/default"), newPost);

      try change this help for me

      Delete
  2. more clear if you share it on youtube video

    ReplyDelete
  3. Hi, i get this error. Please help me

    {"Execution of authentication request returned unexpected result: 404"}

    ReplyDelete
  4. Know the features, advantages and the major difference between Java and Python with the emphasized examples from the best software training institute in Chennai, Infycle Technologies. Dial +91-7504633633 or +91-7502633633 to know the best offers and get the free demo for the combo of Python + Java

    ReplyDelete