How to create articles on Blogspot with C#

Blogger C# API LogoToday I want to show you how to create a blog article on Blogger.com/Blogspot.com with C#. For this you need first of all the Google.GData.Client.dll, which you can find inside the Google .Net API package.

You can download the API package here from Google. (The file is called Google_Data_API_Setup_2.2.0.msi (Please note that the version number – 2.2.0 – over time may change of course.)

If the download is complete, install the package, open a new project in Visual Studio and add a reference to the Google.GData.Client.dll.

The .dll file can be found in the installation directory of the API package. (Click on the link “add a reference” above, if you need help embedding .dlls into a Visual Studio project.)

If you have included the DLL, you can start already. Blog posts (aka articles) can be created as follows:

private static int AddPost(string title,
                                   string html,
                                   string[] labels,
                                   string user,
                                   string pass,
                                   string blogUrl
                                   bool isDraft)
{
	try
	{
		//Is needed to bypass a certificare error
		ServicePointManager.ServerCertificateValidationCallback =
			new RemoteCertificateValidationCallback
			(
				delegate { return true; }
			);


		Service service = new Service("blogger", "api_test");
		service.Credentials = new GDataCredentials(user, pass);

		//Create a blog article
		AtomEntry newPost = new AtomEntry();

		//Set blog post's title
		newPost.Title.Text = title;

		//Create blog post's content
		newPost.Content = new AtomContent();

                //Replace "new lines" with <br />
		string[] breaks = new string[] { "rn", "r", "n" };
		foreach (string breakStr in breaks)
		{
			while (html.Contains(breakStr))
				html = html.Replace(breakStr, "<br/>");
		}
		newPost.Content.Content = html;
		newPost.Content.Type = "html";

		//Set up tags/labels
		foreach (string labelRaw in labels)
		{
			AtomCategory cat = new AtomCategory();
			cat.Scheme = new Uri("http://www.blogger.com/atom/ns#");

			string label = labelRaw;
			string[] forbiddenChars = new string[] { "&", "<", ">", "@", "!", "," };
			foreach (string forbiddenChar in forbiddenChars)
			{
				while (label.Contains(forbiddenChar))
					label = label.Replace(forbiddenChar, "");
			}
			cat.Term = label;
			newPost.Categories.Add(cat);
		}

		newPost.IsDraft = isDraft;

		AtomEntry response = null;
		try
		{
			//Post article
			response = service.Insert(new Uri(blogUrl), newPost);
		}
		catch (GDataRequestException iDontCare)
		{
			if (iDontCare.ResponseString == "Blog has exceeded rate " +
					                "limit or otherwise requires word " +
					         	"verification for new posts")
			{
				//This error happens if you have exceeded your daily post limit
				return -2;
			}
			else
			{
				//Another error
				throw iDontCare;
			}
		}
		if (response == null)
		{
			throw new Exception("Can't create connection.");
		}

		//Blog post successful added to blog
		return 0;
	}
	catch
	{
		return -1;
	}
}

Now we have made the most of! To post a blog article now, we only have to call the newly written function. That might look like this:

Demo.AddPost("This is my first articles heading",
             "<b>that</b><br /><i>is</i> a test",
             new string[] { "test", "csharp", "api" },
             "johndoe@gmail.com",
             "demo_password",
             "https://www.blogger.com/feeds/XXXXXX/posts/default");

One last question is now still in the room. What is the blog url and where does it come from? We now clarify. The url is always the same basic structure. Only the XXXXXX must be replaced with the ID of the blog.

One solution to get the complete URL, I want to show you below. Suppose your blog has the URL: http://code-bude-test.blogspot.com – then “code-bude-test” is the name of the blog that we need now.

public static string SelectUserBlogPostUrl(string subdomain,
                                                   string user,
                                                   string pass)
{
	ServicePointManager.ServerCertificateValidationCallback =
		new RemoteCertificateValidationCallback
		(
			delegate { return true; }
		);
	Service service = new Service("blogger", "api_test");
	service.Credentials = new GDataCredentials(user, pass);

	//Get a list with all blogspot blogs
	FeedQuery query = new FeedQuery();
	query.Uri = new Uri("http://www.blogger.com/feeds/default/blogs");
	AtomFeed feed = service.Query(query);

	string blogUrl = string.Empty;
	if (feed != null)
	{
		foreach (AtomEntry entry in feed.Entries)
		{
			if (entry.AlternateUri.Content.Contains(subdomain))
			{
				for (int i = 0; i < entry.Links.Count; i++)
				{
					if (entry.Links[i].Rel.Equals("http://schemas.google.com/g/2005#post"))
					{
						blogUrl = entry.Links[i].HRef.ToString();
					}
				}
				return blogUrl;
			}
		}
	}
	return blogUrl;
}

Now we have everything together. With the above functions you can now find the blog post url and publish blog posts on Blogger.com.

Finally, a few words about the “rate-limit” (aka “Blog has exceeded rate limit or otherwise requires word verification for new posts“). The Blogger API allows only a certain number of posts per day. An exact number is not given out by Google. However, from experience, I can say that there are almost exactly 50 items, which you can publish per day. After that you aren’t able to post articles by using the Google API.

However, more articles can be published via the web interface of Blogger.com. In the case the limit is reached, however, you must every time you publish an article, solve a captcha. The limit is pretty much set back after 24 hours.

So, that’s about it really for now. If you have suggestions, ideas or any questions, just write a comment.

5 Comments

  1. Fluffy dogsays:

    Hi guys I’m starting a blog here so if u could show me or tell me tips on having a blog that will be gr8t remember stay AWESOME

  2. Also Help me in attaching image in post.

  3. Hi this is very nice article/tut and very useful thank you for this. I have one more question how can we retrieve the url of the post we have made via api. any idea? I am just able to create new post but can’t retrieve it’s URL.

    • Hi saqib,

      have a look at the function to get the blog url (“SelectUserBlogPostUrl”). You can change these to get the url of the latest post. When iterating over all posts (“foreach (AtomEntry entry in feed.Entries)”) then you have to ´watch in every entry-object for the post date and if it’s the newest, than take the url.

      If you wan’t to attach an image, than you have to upload it on an online storage. After that you can embed into your blogpost by using standard html tags like

      Greets,
      Raffi

      • Thank you for reply. Ya after two hours googling I have understand that I must have to learn PICASA API so I must have to upload my image there and gets it’s URL after that I have to use img tag in my html post. :-(
        well before API I was using simple “Email2Post” method it’s much easier than API no headache about uploading image separately.
        Well thanks again good bye.

Leave a comment

Please be polite. We appreciate that. Your email address will not be published and required fields are marked