Translate

Tuesday, 15 July 2014

Blogger post from ASP.Net

Sample post! It looks like setting a draft post to false on the AtomEntry object does not work or it is simply a matter of providing the postId alongwith the blogId and not setting the URL to default feeds.

Below is the code: (you can use NUGet to install the Google API into your VS project)

using System;
using Google.GData.Client;
using System.Web.UI;

namespace BloggerPost
{
    public partial class _Default : Page
    {
        string blogId = ""; // This id will be part of the query string in your browser address bar when you access your blog
        string username;
        string password;
        private void PostOrUpdateBlogPost(string yourBlogId,bool isUpdate)
        {
            if (yourBlogId != null)
            {
                var service = new Google.GData.Client.Service("","Application Name");
                service.Credentials = new GDataCredentials(username, password);
                AtomEntry newPost = null;
                if (isUpdate)
                {
                    try
                    {
                        // need to correct the URL here
                        newPost = service.Get(yourBlogId);
                        newPost.Categories.Clear();
                        // Setting the isDraft property requires the above URL to contain the postId (need to confirm test this).
                        if (newPost.IsDraft) newPost.IsDraft = false;
                    }
                    catch (Exception ex)
                    {

                    }
                }
                else
                {
                    newPost = new AtomEntry();
                    newPost.Title.Text = "Blogger post from ASP.Net";
                    newPost.Content = new AtomContent();
                    newPost.Content.Content = "Sample post! It looks like setting a draft post to false on the AtomEntry object does not work or it is simply a matter of providing the postId alongwith the blogId and not setting the URL to default feeds.";
                    newPost.Content.Type = "html";
                }
             
                try
                {
                    if (!isUpdate)
                    {
                        Uri blogPostUri = new Uri("http://www.blogger.com/feeds/" + yourBlogId + "/posts/default");
                        newPost = service.Insert(blogPostUri, newPost);
                    }
                    else
                    {
                        newPost = newPost.Update();
                    }
                }
                catch (Exception ex)
                {              
                }
            }
        }
 
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                PostOrUpdateBlogPost(blogId,false); // the boolean is to specify if it is a new post or an update.
            }
        }
 
    }
}

No comments: