December 12th 2009 Getting Your Latest Tweets – Silverlight (No API Key!)

Getting your latest tweets from Twitter and importing them into your Silverlight application is easier than I thought when I set about writing some code. There is a wealth of information you can gain from the Twitter API – I would suggest spending some time getting to know the API, you’ll be pleasantly surprised with what you can do with it.

The easiest way to get your latest 20 tweets is to write a web service, then consume that service from your Silverlight application.  I chose to simply make the call to the API, then pass the results back as a list of strings.  I have listed the code for a sample web service below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Xml.Linq;

namespace GetLatestTweets
{
    /// <summary>
    /// Summary description for GetMyTweets
    /// </summary>
    [WebService(Namespace = "http://yourwebsite.com/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    public class GetMyTweets : System.Web.Services.WebService
    {
        [WebMethod]
        public List<string> GetTweets(string UserID)
        {
            XElement xml = XElement.Load("http://twitter.com/statuses/user_timeline.xml?screen_name=" + UserID);
            var Tweets = from t in xml.Elements()
                         where t.Name.LocalName == "status"
                         select t;

            List<string> tweets = new List<string>();
            foreach (var t in Tweets)
            {
                tweets.Add(t.Element("text").Value);
            }
            return tweets;
        }
    }
}

Things to note:

  1. Use the XElement object to load the XML returned by the API call.
  2. Use a LINQ query to parse the results, first grabbing the “status” element, then finding the “text” subelement.
  3. Add the value from this element to the result set.
  4. Take the results, and parse through each, adding them to a new list of strings.
  5. Return the list of strings.

Consuming the service is just as easy:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.ServiceModel;              // for calling the webservice
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace RecentTweets
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();

            GetTweets("[Your Twitter User ID]");  // call the GetTweets method
        }

        protected void GetTweets(string userID)
        {
            // create an instance of the web service
            GetTweetsService.GetMyTweetsSoapClient client = new RecentTweets.GetTweetsService.GetMyTweetsSoapClient(new BasicHttpBinding(), new EndpointAddress(new Uri("[URL to the WebService]",UriKind.Absolute)));
           // create a delegate to indicate the webservice has completed its call
           client.GetTweetsCompleted += new EventHandler<RecentTweets.GetTweetsService.GetTweetsCompletedEventArgs>(client_GetTweetsCompleted);
           // get the latest tweets
           client.GetTweetsAsync();
        }

        protected void client_GetTweetsCompleted(object sender, RecentTweets.GetTweetsService.GetTweetsCompletedEventArgs e)
        {
            // when the webservice call is complete, parse through each result
            for (int i = 0; i < e.Result.Count; i++)
            {
                // create a new textblock to hold the tweet
                TextBlock text = new TextBlock();
                // set the text of the textblock to the text of the tweet
                text.Text = e.Result[i];
                // add the textblock to the stackpanel
                Tweets.Children.Add(text);
            }
        }
    }
}

The only other part to this code is the XAML of the Silverlight application. It consists of a stackpanel in a scrollviewer which holds the tweets. Here is the code:

<UserControl x:Class="RecentTweets.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" d:DesignWidth="150" d:DesignHeight="125">
  <ScrollViewer>
  	<StackPanel x:Name="Tweets"/>
  </ScrollViewer>
</UserControl>

If you have any questions, feel free to shoot me an email.

    Filed under Code Samples

    December 4th 2009 My First Flex Application

    I decided today that I would try to learn some Adobe Flex®. I started watching some videos of the “Learn Flex in a Week” series, to gain a better understanding of Flex, and try to write some code.  My first application (which is featured in videos) is VERY simple. It is an employee manager which takes the values from the home address and puts them into the mailing address fields when a user checks a checkbox control.  The form does not submit (yet), and there really isn’t any error checking (except for emptying the fields if the user unchecks the box), but it is a basic example which I thought I would post to show how easy it can be.

    I am a Silverlight® designer, and I have noticed that the way Flex behaves is very similar, and I think that I should be able to catch on relatively quickly.

    Without further adieu, here it is:

    Right-click the app, and select “view source” for the source code to this project.

      Filed under Code Samples