Twitter Search application for Windows Phone 7

DZone 's Guide to

Twitter Search application for Windows Phone 7

· Mobile Zone ·
Free Resource

In this lesson I will create a simple Twitter search application for Windows Phone 7. Basically, tutorial is very similar to my previous my RSS tutorial, but instead of RSS feed, I am going to use one of the Twitter API methods. This application will allow user to search for twitter entries containing a specified keyword. Application will implement one of the Twitter REST API‘s methods. Selected method is public, so you don’t need Twitter to authorize you for using it. Let’s begin!

Source code

Additional information

1. Creating a new project

First of all you need to create a new project. To do so open Visual Studio 2010 -> File -> New Project -> select Windows Phone Application there as it is shown on picture bellow.

eugenedotnet creating windows phone 7 project

2. Adding a new reference to solution

Next you need to add a reference to Microsoft.Xml.Linq library. You need to right click on the References directory under your project and select Add Reference there. Under .NET tab you will find Microsoft.Xml.Linq, push OK. Check screenshot bellow.

eugenedotnet add Microsoft.Xml.Linq reference

3. Modifying header (optional)

This step can be optional, but I have decided to add it to the lesson. In this step we simply modify TitleGrid element to specify the title of application.

<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="24,24,0,12">
   <TextBlock x:Name="ApplicationTitle" Text="EUGENEDOTNET.COM" Style="{StaticResource PhoneTextNormalStyle}" Margin="0, 0, 0, 0"/>
   <TextBlock x:Name="PageTitle" Text="Twitter App" Margin="-3,-8,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>

4. Modifying ContentGrid

ContentGrid will contain all the required User Interface elements to operate with our application. There will be three main elements:

  • TextBox for user to enter a keyword to search for. It will be a custom textbox containing DefaultText property (described [WP7HTextBox|here].
  • Button to trigger an event to search
  • ListBox to display results using Data Binding feature of Silverlight (e.g {Binding Title} binds an attribute value to a Title property of an object ). ListBox will display an image, user name and a text of twitter entry.

NB! Pay attention that click event is added to a button in XAML.

<Grid x:Name="ContentGrid" Grid.Row="1">
                <RowDefinition Height="Auto" />
                <RowDefinition Height="*" />
            <Grid x:Name="gridFilter" Grid.Row="0">
                    <RowDefinition Height="*" />
                    <RowDefinition Height="*" />
                <Grid Grid.Row="0">
                        <ColumnDefinition Width="*" />
                        <ColumnDefinition Width="140" />
                    <local:EDAdvancedTextbox x:Name="tbTweetSearch" Grid.Column="0"  DefaultText="enter keyword to search..." />
                    <Button Width="140" x:Name="btnTweetSearch" Grid.Column="1" Content="Search" Click="btnTweetSearch_Click" />
                <ScrollViewer Grid.Row="1">
                    <ListBox Name="lbTwitterEntries" Width="440" Height="530">
                                        <ColumnDefinition Width="60" />
                                        <ColumnDefinition Width="*" />
                                        <RowDefinition Height="*" />
                                        <RowDefinition Height="20" />
                                    <Image HorizontalAlignment="Left" VerticalAlignment="Top" Grid.Row="0" Source="{Binding AuthorImage}"  Grid.Column="0" />
                                    <Grid Grid.Column="1" Grid.Row="0">
                                            <RowDefinition Height="*" />
                                            <RowDefinition Height="*" />
                                            <RowDefinition Height="*" />
                                        <HyperlinkButton HorizontalAlignment="Left" Margin="10,0,0,0" Content="{Binding AuthorName}" FontSize="20" Grid.Row="0" NavigateUri="{Binding AuthorUri}" />
                                        <TextBlock Margin="10,0,0,0" Text="{Binding Title}" FontSize="24" TextWrapping="Wrap" Grid.Row="1" />

5. Adding a constant for a search method URL

Next we need to add a constant containing a template path to Twitter API search method. Later we can simply add a keyword instead of {0} using String.Format.

const string TWITTER_SEARCH_URL = "http://search.twitter.com/search.atom?rpp=25&q={0}";

6. Creating a class for a single Twitter entry

Now we simply need to create a new container-class for holding Twitter entry data.

public class TwitterEntry
    public string ID { get; set; }
    public string Title { get; set; }
    public DateTime Date { get; set; }
    public string AuthorName { get; set; }
    public string AuthorUri { get; set; }
    public string AuthorImage { get; set; }

7. Implementing a Click event

Next we need to write a code for processing “Search” button click event. It should create a new URI object based on a keyword and pass it to SearchTwitterEntries method. HttpUtility will encode an URL and make it special-character-safe.

private void btnTweetSearch_Click(object sender, RoutedEventArgs e)
    if (!string.IsNullOrEmpty(tbTweetSearch.Text.Trim()))
        string searchText = HttpUtility.UrlEncode(tbTweetSearch.Text.Trim());
        SearchTwitterEntries(new Uri(string.Format(TWITTER_SEARCH_URL, searchText), UriKind.Absolute));

8. Implementing search functionality

First of all make sure that MainPage.xaml class (codebehind) is using the following references.

// for reading and parsing Twitter entries using Linq-To-XML
using System.Xml.Linq;
// for Stream object
using System.IO;

After that you need to implement a SearchTwitterEntries method that takes URI (URL) as an input parameter. If request is successful then application will process results of Twitter entry search and add them using ForEach to a listbox. ListBox will display results according to the Data Binding specified above. Pay attention that most of WebClient methods are asynchronous. Parsing is done using Linq-TO-XML.

public void SearchTwitterEntries(Uri twitterSearchUri)
    WebClient wclient = new WebClient();
    wclient.OpenReadCompleted += (sender, e) =>
        if (e.Error != null)
        Stream str = e.Result;
        XElement xelem = XElement.Load(str);
        XNamespace atomNS = "http://www.w3.org/2005/Atom";
        List<TwitterEntry> twitterEntries = (from entry in xelem.Descendants(atomNS + "entry")
            select new TwitterEntry()
                ID = entry.Element(atomNS + "id").Value,
                Title = entry.Element(atomNS + "title").Value,
                Date = DateTime.Parse(entry.Element(atomNS + "published").Value),
                AuthorName = entry.Descendants(atomNS + "author").Elements(atomNS + "name").FirstOrDefault().Value,
                AuthorUri = entry.Descendants(atomNS + "author").Elements(atomNS + "uri").FirstOrDefault().Value,
                AuthorImage = (from imgElement in entry.Elements(atomNS + "link")
                    where imgElement.Attribute("rel") != null
                    && imgElement.Attribute("rel").Value.Contains("image")
                    && imgElement.Attribute("href") != null
                    select imgElement.Attribute("href").Value).FirstOrDefault()
        // close
        // add results to listbox
        twitterEntries.ForEach(item => lbTwitterEntries.Items.Add(item));

Source:  http://www.eugenedotnet.com/2010/08/twitter-search-application-for-windows-phone-7/

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}