DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations

Twitter Search application for Windows Phone 7

Jevgeni Tšaikin user avatar by
Jevgeni Tšaikin
·
Nov. 21, 11 · Interview
Like (0)
Save
Tweet
Share
4.70K Views

Join the DZone community and get the full member experience.

Join For Free

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

  • Twitter search application for Windows Phone source code (.zip)

Additional information

  • What is Twitter? (Wikipedia)
  • Official Twitter Website
  • Twitter REST API
  • Twitter API Search method
  • Data Binding in Silverlight
  • Default Text for a TextBox in Windows Phone 7 apps


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}"/>
</StackPanel>

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">
 
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition Height="*" />
            </Grid.RowDefinitions>
 
            <Grid x:Name="gridFilter" Grid.Row="0">
 
                <Grid.RowDefinitions>
                    <RowDefinition Height="*" />
                    <RowDefinition Height="*" />
                </Grid.RowDefinitions>
 
                <Grid Grid.Row="0">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*" />
                        <ColumnDefinition Width="140" />
                    </Grid.ColumnDefinitions>
                    <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" />
                </Grid>
                <ScrollViewer Grid.Row="1">
                    <ListBox Name="lbTwitterEntries" Width="440" Height="530">
                        <ListBox.ItemTemplate>
                            <DataTemplate>
                                <Grid>
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="60" />
                                        <ColumnDefinition Width="*" />
                                    </Grid.ColumnDefinitions>
                                    <Grid.RowDefinitions>
                                        <RowDefinition Height="*" />
                                        <RowDefinition Height="20" />
                                    </Grid.RowDefinitions>
                                    <Image HorizontalAlignment="Left" VerticalAlignment="Top" Grid.Row="0" Source="{Binding AuthorImage}"  Grid.Column="0" />
                                    <Grid Grid.Column="1" Grid.Row="0">
                                        <Grid.RowDefinitions>
                                            <RowDefinition Height="*" />
                                            <RowDefinition Height="*" />
                                            <RowDefinition Height="*" />
                                        </Grid.RowDefinitions>
                                        <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" />
                                    </Grid>
 
                                </Grid>
                            </DataTemplate>
                        </ListBox.ItemTemplate>
                    </ListBox>
                </ScrollViewer>
            </Grid>
 
</Grid>

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)
            return;
 
        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()
            }).ToList();
 
        // close
        str.Close();
 
        // add results to listbox
        lbTwitterEntries.Items.Clear();
        twitterEntries.ForEach(item => lbTwitterEntries.Items.Add(item));
    };
    wclient.OpenReadAsync(twitterSearchUri);
}

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

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Secure APIs: Best Practices and Measures
  • What Is the Temporal Dead Zone In JavaScript?
  • Mocha JavaScript Tutorial With Examples for Selenium Testing
  • What Is Automated Testing in Software Testing?

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: