Showing posts with label Google Blogs API. Show all posts
Showing posts with label Google Blogs API. Show all posts

Aug 14, 2008

Skype4COMLib and Blogger - get your posts as a mood text in skype (or do whatever you want with skype ;).

My dear friend Bobby is going on vacation today at 6 p.m. Since I’m going to miss her while she’s taking her vacation on Black Sea I decided to play a bit with Skype4COM and write a small program for her.


This is where everything started ;) (thanks, Bobby for the inspiration ;).
She had her skype mood text set to how many days are until her vacation takes place. I wanted to help her so I wrote a simple tool to countdown until 6 p.m. and change her Skype mood accordingly.

Well I am not going to explain you how I did this. I got better idea later. I decided to make a mood changer for me. The mood changer will take my blogger posts and rotate them as skype mood text.

Skype Mood Text Changer, made with Skype4COM Lib and .NET C#

First of all, where should I get my posts from? Well, there are two ways I can think of. The first one is to use the Blogger API (login with the user, get all user blogs, get all user posts, etc.).
The second one is to use the RSS feed that blogger automatically creates for each blog.
Since this is very small tool I think the first approach is too “heavy” and “complex”. After all we aren’t going to post to the blog or anything that will require us to login in Blogger. So I took the RSS approach.

Let’s see how you can create a small program to do this for you:
1. Start new windows application.
2. Right click your References folder in the solution explorer and choose Add Reference …
3. In the dialog box click on the “COM” tab and find Skype4COMLib.
4. Click OK.

Now you have that skype thing referenced in your project. Add it to your using clause:

using SKYPE4COMLib;

After we are here, and we know we are going to use RSS, we will need Xml namespace as well. Add it too:

using System.Xml;

Okay. In my approach, I wanted to display random post on every 10 seconds. This means I will need to store a post title -> post link pair somewhere. I did this in a generic List of string[] arrays. I am not quite sure how optimized is this but this is only sample and it works fine for me. If you can think of something more optimized - please do not hesitate to write a comment ;). For now, however, add the System.Collections namespace to your using clause:

using System.Collections;

Okay, we have everything we will need to create our small tool. Now add a timer on your form. It’s timer1 in my sample. Set it's interval to 10000 (10 seconds).

Add the following global variables to your project:

List<string[]> posts = new List<string[]>();
private SKYPE4COMLib.Skype skype;

Here is how your Form_Load event should look like:

    
private void Form1_Load(object sender, EventArgs e)
     {
        skype =
new SkypeClass();
        
this.WindowState = FormWindowState.Minimized;
        GetBlogs();
        timer1.Enabled =
true;
     }

What I want you to note in the Page_Load is that I am assigning the skype variable. This way it will remain linked to your skype until the program is runned.

I used routine GetBlogs() in this project, here is it:

private void GetBlogs()
{
XmlDocument docRSS = new XmlDocument();
docRSS.Load(
"http://donchevp.blogspot.com/feeds/posts/default?alt=rss");
    
foreach (XmlNode nodeItem in docRSS.SelectNodes("/rss/channel/item"))
    {
    
string title = nodeItem.SelectSingleNode("title").InnerText;
        
string href = nodeItem.SelectSingleNode("link").InnerText;
posts.Add(
new string[] { href, title });
    }

}


NOTE: replace the url in the docRSS.Load() method, otherwise you will promote my blog ;).

This routine simply takes all the posts and stores them in the List of string arrays as link, title pairs.
Now we need to display the posts as title “-“ link. This will happen in the timer1_Tick event:

private void timer1_Tick(object sender, EventArgs e)
{
int iPostIndex = int.MinValue;
    
if (posts.Count > 0)
    {
    
Random rnd = new Random();
        iPostIndex = rnd.Next(0, posts.Count);
        skype.CurrentUserProfile.MoodText = posts[iPostIndex][1] +
" - " + posts[iPostIndex][0];
}
}

Everything seems to work fine now. Run your program. Skype should ask you if you are sure you want to give access to this program to use skype. Agree with that. You should now see your posts rotating each 10 seconds.

Here is the complete code (I will also upload the project on Chameleon Bulgaria site, as codes in Blogger doesn’t appear very smoothly):

Form1.cs:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using SKYPE4COMLib;
using System.Xml;
using System.Collections;

namespace dayOffCounter
{
  
public partial class Form1 : Form
   {
    
List<string[]> posts = new List<string[]>();
    
private SKYPE4COMLib.Skype skype;
    
public Form1()
     {
        InitializeComponent();
     }

    
private void Form1_Load(object sender, EventArgs e)
     {
        skype =
new SkypeClass();
        
this.WindowState = FormWindowState.Minimized;
        GetBlogs();
        timer1.Enabled =
true;
     }

    
private void GetBlogs()
     {
        
XmlDocument docRSS = new XmlDocument();
        docRSS.Load(
"http://donchevp.blogspot.com/feeds/posts/default?alt=rss");
        
foreach (XmlNode nodeItem in docRSS.SelectNodes("/rss/channel/item"))
        {
          
string title = nodeItem.SelectSingleNode("title").InnerText;
          
string href = nodeItem.SelectSingleNode("link").InnerText;

           posts.Add(
new string[] { href, title });
        }
     }

    
private void timer1_Tick(object sender, EventArgs e)
     {
        
int iPostIndex = int.MinValue;
        
if (posts.Count > 0)
        {
          
Random rnd = new Random();
           iPostIndex = rnd.Next(0, posts.Count);
           skype.CurrentUserProfile.MoodText = posts[iPostIndex][1] +
" - " + posts[iPostIndex][0];
        }
     }
   }
}

Things to consider: Unfortunately skype has some constraints we can not avoid. First of all - the text seems to be too short to hold some of my posts, which results in links not being rendered correctly and leading to a wrong page (or even worse - to a page that doesn’t exist). I really wish to be able to set click here links as a mood text but it is not possible for now (at least I couldn’t find such functionality).

Happy codding!

Jan 13, 2008

Another 5 minutes with C# to post to Google Blogs (Blogger.com) using Google Blogs SDK (2)

I revised the tool a bit, here is how it looks now:





Also I made some refactoring to the code and it looks better now (no more richTextBox1 names ;).
I plan to release this tool in order to help developers blog code to their blogger accounts easier. The next secret I am going to reveal is that I started a toolkit to help you create blog related programs with C# / .NET / Google Blogs API.

For now I am planning to release the program for free, as a Lite version and I plan to spend some more time to create a better looking version with SEO features in it and distribute it for a small fee (something like 10 EU).
The Toolkit will released for free now.

Well that's it. I am looking forward when I will have some more time to develop those
controls and programs to help the Blogger community grow ;)

Jan 10, 2008

5 minutes with C# - Get your blog in TreeView Control

I played a bit more with the Google Blogs Api and was able to create a custom TreeView control to help you get your blog in Hierarchical View.

Here is a screenshot of the TreeView:



The control will be soon released to my site and new blog post will be published to let you know
.

Another 5 minutes with C# to post to Google Blogs (Blogger.com) using Google Blogs SDK

             // Create service to be used for queries
             Service service = new Service ( "blogger" , "blogger-sample" );
            
AtomEntry createdEntry = new AtomEntry ();
            
// Create credentials you should add your blog username
             // and password here
            service.Credentials = new GDataCredentials ( "your_username" , "your_password" );

            
// As I only have one blog to speed up - I am taking it,
             // You can extend here in order to allow the user to
             // select from mutliple
blogs if he / she has.
             Uri firstBlogUri = GetFirstBlogUri(service);
            
            
// If we have the Uri - it's time to actually post.
             if (firstBlogUri != null )
            {
               
// Create FeedQuery and assign Uri.
                FeedQuery query = new FeedQuery ();
                query.Uri = firstBlogUri;

               
// Create Atom Feed from that query.
                AtomFeed feed = service.Query(query);

               
// Create atom entry for the new post
                AtomEntry newPost = new AtomEntry ();

               
// Fill in the post information
                // You need to have a control named richTextBox2 which will
                // contain the post body and a textBox1 control which will
                // contain the post title.

                newPost.Title.Text = this .textBox1.Text;
                newPost.Content =
new AtomContent ();
                newPost.Content.Content = richTextBox2.Text;
                newPost.Content.Type =
"html" ;
                newPost.Authors.Add(
new AtomPerson ());
                newPost.Authors[0].Name =
"Pavel Donchev" ;

               
// Try to publish and report success / fail:
                try
                {
                   createdEntry = service.Insert(query.Uri, newPost);
                }
               
catch ( Exception ex)
                {
                  
MessageBox .Show(ex.Message);
                }
               
if (createdEntry != null )
                {
                  
MessageBox .Show(newPost.Title.Text + " posted successfully!" );
                }
            }

There is also a helper function to retrieve the blog Uri:

      
Uri GetFirstBlogUri( Service service)
       {
            
FeedQuery query = new FeedQuery ();
            
// Retrieving a list of blogs
            query.Uri = new Uri ( "http://www.blogger.com/feeds/default/blogs" );

            
AtomFeed feed = null ;
            feed = service.Query(query);
            
AtomEntry entry = feed.Entries[0];
            
for ( int i = 0; i < entry.Links.Count; i++)
            {
               
if (entry.Links[i].Rel.Equals( "http://schemas.google.com/g/2005#post" ))
                {
                  
return new Uri (entry.Links[i].HRef.ToString());
                }
            }
            
return null ;
       }

Jan 8, 2008

5 minutes C# code to help you blog source ...

As I was unabled to find a reliable editor to convert my code samples to html, I decided to write one. You need two richTextBox components, named richTextBox1 and richTextBox2 and a Button, named button1.

Here is the code you need to put into the button1 click event handler:
       private void button1_Click(object sender, EventArgs e)
       {
            
string oldColor = "-";
            
string newColor = string.Empty;

            
StringBuilder strHtml = new StringBuilder();

            
for (int i = 0; i < this.richTextBox1.Text.Length; i++)
            {
                richTextBox1.Select(i, 1);
               
newColor = System.Drawing.ColorTranslator.ToHtml(richTextBox1.SelectionColor);
               
if ((newColor != oldColor) && (newColor != string.Empty))
                {
                  
if (!oldColor.Equals("-"))
                   {
                        strHtml.Append(
"");
                   }
                   strHtml.Append(
" + newColor + ";\">");
                   oldColor = newColor;
                }
                strHtml.Append(richTextBox1.SelectedText.Replace(
"<", "<").Replace(">", ">"));
               
Application.DoEvents();
            }
            strHtml.Append(
""
);
            
StringBuilder sbNew = new StringBuilder();
            sbNew.Append(strHtml.ToString().Replace(
"   ", "   "));
            richTextBox2.AppendText(sbNew.ToString());
       }


PLEASE NOTE: this code was written in 5 or 10 minutes, it doesn't pretend to be either clean or readable, it simply works. If you want - you can take it, optimize it, use it or whatever, just have in mind it wasn't written carefully ;).