Click here to Skip to main content
15,886,773 members
Articles / Mobile Apps / Windows Phone 7

Searching Twitter on Windows Phone 7

Rate me:
Please Sign up or sign in to vote.
4.69/5 (5 votes)
24 Feb 2011Ms-PL2 min read 12.6K   2   2
Searching Twitter on Windows Phone 7

In the previous post, we’ve seen how to get a list of trends on twitter.
In this post, we continue to explore twitter service. We will see how to search for twits on twitter.

image

Searching Twitter

Twitter exposes a JSON-based search service in the following address:

where {0} should be replaced with your search term.

The results are returned in JSON data format, so we will use again the DataContractJsonSerializer. For more details on how to use it, check out the previous post.

Defining Twit and TwitterResults

Similarly to what we’ve done in the previous post, we need to declare some C# model classes that will be used to parse the twitter JSON results.

C#
/// <summary>
/// Model for twit
/// </summary>
public class Twit
{
    /// <summary>
    /// Gets or sets the text.
    /// </summary>
    /// <value>The text.</value>
    public string text { get; set; }

    /// <summary>
    /// Gets the decoded text.
    /// </summary>
    /// <value>The decoded text.</value>
    public string DecodedText 
    {
        get
        {
            return HttpUtility.HtmlDecode(text);
        }
    }

    /// <summary>
    /// Gets or sets the from_user.
    /// </summary>
    /// <value>The from_user.</value>
    public string from_user { get; set; }

    /// <summary>
    /// Gets or sets the profile_image_url.
    /// </summary>
    /// <value>The profile_image_url.</value>
    public string profile_image_url { get; set; }

    /// <summary>
    /// Gets or sets the created_at.
    /// </summary>
    /// <value>The created_at.</value>
    public DateTime created_at { get; set; }
}

/// <summary>
/// Model for twitter results
/// </summary>
public class TwitterResults
{
    /// <summary>
    /// Gets or sets the results.
    /// </summary>
    /// <value>The results.</value>
    public Twit[] results { get; set; }
}

Note that the twit text should be HTML-decoded before using it, so I’ve added a DecodedText property to do the job.

Implement the Twitter Search Service

We will implement a static method named TwitterService.Search that will receive the search term as its first parameter and a few delegates to allow our class to work asynchronously:

  • Action<IEnumerable<Twit>> onSearchCompleted, which will be called when the twitter search is complete.
  • Action<Exception> onError, which will be called if there is an error while searching twitter.
  • Action onFinally, which will be called always, whether there was an exception or not. Think of it as the finally section on a common try-catch block.

So the method signature will be:

C#
public static void Search(string searchText, Action<IEnumerable<Twit>> 
onSearchCompleted = null, Action<Exception> onError = null, Action onFinally = null)

To search twitter, we will use the WebClient class, yet again:

C#
WebClient webClient = new WebClient();

// register on download complete event
webClient.OpenReadCompleted += delegate(object sender, OpenReadCompletedEventArgs e)
{
    ...
};

string encodedSearchText = HttpUtility.UrlEncode(searchText);
webClient.OpenReadAsync(new Uri
(string.Format(TwitterSearchQuery, encodedSearchText)));

where TwitterSearchQuery is defined as follows:

C#
private const string TwitterSearchQuery = 
"http://search.twitter.com/search.json?q={0}";

The rest of the code handles the different delegates: on SearchCompleted, onError, onFinally. I bring here the method in its full:

C#
/// <summary>
/// Searches the specified search text.
/// </summary>
/// <param name="searchText">The search text.</param>
/// <param name="onSearchCompleted">The on search completed.</param>
/// <param name="onError">The on error.</param>
public static void Search(string searchText, 
Action<IEnumerable<Twit>> onSearchCompleted = null, 
Action<Exception> onError = null, Action onFinally = null)
{
    WebClient webClient = new WebClient();

    // register on download complete event
    webClient.OpenReadCompleted += delegate(object sender, 
				OpenReadCompletedEventArgs e)
    {
        try
        {
            // report error
            if (e.Error != null)
            {
                if (onError != null)
                {
                    onError(e.Error);
                }
                return;
            }

            // convert json result to model
            Stream stream = e.Result;
            DataContractJsonSerializer dataContractJsonSerializer = 
			new DataContractJsonSerializer(typeof(TwitterResults));
            TwitterResults twitterResults = 
		(TwitterResults)dataContractJsonSerializer.ReadObject(stream);

            // notify completed callback
            if (onSearchCompleted != null)
            {
                onSearchCompleted(twitterResults.results);
            }
        }
        finally
        {
            // notify finally callback
            if (onFinally != null)
            {
                onFinally();
            }
        }
    };

    string encodedSearchText = HttpUtility.UrlEncode(searchText);
    webClient.OpenReadAsync(new Uri(string.Format
		(TwitterSearchQuery, encodedSearchText)));
}

Using the Twitter Search Service

Using the service is easy:

C#
TwitterService.Search(
    textbox.Text,
   (items) => { listbox.ItemsSource = items; },
   (exception) => { MessageBox.Show(exception.Message); },
   null
   );

There is a sample application which can be downloaded here.

Note: This code was first published as part of the “Using Pivot and Panorama Controls” lab found in the Windows Phone Training Kit for Developers, which I wrote for Microsoft.

That’s it for now,
Arik Poznanski.

License

This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL)


Written By
Software Developer (Senior) Verint
Israel Israel
Arik Poznanski is a senior software developer at Verint. He completed two B.Sc. degrees in Mathematics & Computer Science, summa cum laude, from the Technion in Israel.

Arik has extensive knowledge and experience in many Microsoft technologies, including .NET with C#, WPF, Silverlight, WinForms, Interop, COM/ATL programming, C++ Win32 programming and reverse engineering (assembly, IL).

Comments and Discussions

 
GeneralMy vote of 5 Pin
mbcrump24-Mar-11 7:49
mentormbcrump24-Mar-11 7:49 
GeneralMy Vote of 5 Pin
RaviRanjanKr26-Feb-11 5:23
professionalRaviRanjanKr26-Feb-11 5:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.