Introduction

In today’s post, we are going to write a Twitter app that allows the user to type in a twitter username and display the tweets from the user. We will be using the new Twitter API v1.1 released late last year and use a couple of Telerik’s RadControls for Windows Phone 8. We will also make use of Joe Mayo’s excellent Linq2Twitter library to simplify things.

Let’s get started.

Launch Visual Studio 2012 and select, Visual C#-> Windows Phone -> RadControls for Windows Phone and give it a meaningful name. On the project configuration wizard screen, leave the default component selected as shown in Figure 1 and press next.

1

Figure 1: The First Screen to our RadControls for Windows Phone 8 App.

The second page in the project configuration wizard is shown in Figure 2.

2

Figure 2: The Second Screen to our RadControls for Windows Phone 8 App.

As you can tell from this screen, we have built into the template two of the most common pages in a professional Windows Phone app. The “About” and “How To” page. We have also added the ability to quickly add functionality such as error diagnostics, trial and rate reminders. The error diagnostics will trap any unhandled exceptions and the trial and rate reminders will prompt your users to either purchase the app or rate the app depending on if you desire this functionality or not. We are building a simple first app, so remove all the checkmarks except Diagnostics.

Laying out our UI and Adding Required References.

Our UI will consist of RadTextBox and RadDataBoundListBox. Both of these controls contain the needed functionality to get started quickly. A screenshot of the final app is shown in Figure 3.

 3

Figure 3: Our Final Windows Phone 8 App.

Let’s take a look first at the completed XAML for our ContentPanel in MainPage.xaml:

<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
 
 <Grid.RowDefinitions>
 <RowDefinition Height="80*" />
 <RowDefinition Height="533*" />
 </Grid.RowDefinitions>
 
 <telerikPrimitives:RadTextBox x:Name="txtUserName" Watermark="Enter Twitter UserName" ActionButtonVisibility="Visible" ActionButtonTap="txtUserName_ActionButtonTap" >
 <telerikPrimitives:RadTextBox.ActionButtonStyle>
 <Style TargetType="telerikPrimitives:RadImageButton">
 <Setter Property="ButtonShape" Value="Ellipse"/>
 </Style>
 </telerikPrimitives:RadTextBox.ActionButtonStyle>
 </telerikPrimitives:RadTextBox>
 
 <telerikPrimitives:RadDataBoundListBox Grid.Row="1" Name="lstTwitter" IsPullToRefreshEnabled="True" RefreshRequested="lstTwitter_RefreshRequested">
 <telerikPrimitives:RadDataBoundListBox.ItemTemplate>
 <DataTemplate>
 <StackPanel Orientation="Horizontal" Height="110" Margin="10">
 <Image Source="{Binding ImageSource}" Height="73" Width="73" VerticalAlignment="Top" Margin="10,10,8,10"/>
 <TextBlock Text="{Binding Message}" Margin="10" TextWrapping="Wrap" FontSize="18" Width="320" />
 </StackPanel>
 </DataTemplate>
 </telerikPrimitives:RadDataBoundListBox.ItemTemplate>
 </telerikPrimitives:RadDataBoundListBox> 
</Grid>

We are using RadTextBox to collect data from the end user. By using this control we can easily implement the following features without writing additional code:

  • We added a watermark so the user knows what data this field is expecting.
  • There is a built in button that we can add by setting the ActionButtonVisibility to Visible and adding an event handler on ActionButtonTap.
  • We can easily style the ActionButton to have an Ellipse shape as shown above.
  • After the user starts typing, they can quickly clear the contents by pressing the X in the left hand corner, similar to Windows 8 Textbox fields. (This functionality occurs automatically.)

RadDataBoundListBox will allow our users to have a powerful control that handles many items as well as Pull-To-Refresh functionality. This allows the end-user to request a data refresh by pulling the top edge of the scrollable content down and releasing it. Inside of the ItemTemplate, we are going to create a DataTemplate that contains an Image and a TextBlock. The Image will show the user’s twitter avatar and the TextBlock will contain the text of the tweet.

Now that we have defined our UI, let’s go ahead and pull in the Linq2Twitter library using NuGet. We can right-click on references and select, “Manage NuGet References” then type in linq2twitter and click install as shown in Figure 4.

4

Figure 4: Adding Linq2Twitter to our Windows Phone 8 App.

Once installed, we can check “References” and should see “LinqToTwitterWP”.

A Quick Word on the New Twitter API

Twitter API 1.1 requires authentication on every API endpoint. That means that from now on you will need to create an app that contains your Consumer Key, Consumer Secret, Access Token and Access Token Secret. You can easily create an app by visiting https://dev.twitter.com. Once that is in place, you can get your keys by visiting your apps page.

Note that the developer will have to manually create their access tokens in the app’s settings page as shown in Figure 5.

 2013-07-24_1554

Figure 5: The OAuth Settings Page.

Time to Write Some Code!

Begin by creating a simple class called TwitterItem and adding the following two properties. Make sure you mark the class as public as shown below:

public class TwitterItem
{
 public string ImageSource { get; set; }
 public string Message { get; set; }
}

Switch over to our MainPage.xaml.cs and before our MainPage constructor, we will need to add in the following code:

SingleUserAuthorizer singleUserAuthorizer = new SingleUserAuthorizer()
{
    Credentials = new SingleUserInMemoryCredentials()
    {
        ConsumerKey = "YOUR_CONSUMER_KEY",
        ConsumerSecret = "YOUR_CONSUMER_SECRET",
        TwitterAccessToken = "YOUR_ACCESS_TOKEN",
        TwitterAccessTokenSecret = "YOUR_ACCESS_TOKEN_SECRET"
    }
};

In this snippet, we are using Linq2Twitter to authenticate with Twitter about who we are and it will automatically determine what our permissions are. We can now drop in a method to Load Tweets once the user presses the search button (included in the RadTextBox) or refreshes the list with RadDataBoundListBox. The source code is listed below.

public void LoadTweets()
       {
 if (singleUserAuthorizer == null || !singleUserAuthorizer.IsAuthorized)
           {
               MessageBox.Show("Not Authorized!");
           }
 else
           {
               var twitterCtx=new TwitterContext(singleUserAuthorizer);
 
               (from tweet in twitterCtx.Status
 where tweet.Type == StatusType.User &&
                      tweet.ScreenName == txtUserName.Text
                select tweet)
                             .MaterializedAsyncCallback(asyncResponse => Dispatcher.BeginInvoke(() =>
                               {
 if (asyncResponse.Status != TwitterErrorStatus.Success)
                                   {
                                       MessageBox.Show("Error: " + asyncResponse.Exception.Message);
 return;
                                   }
 
                                   lstTwitter.ItemsSource=
                                       (from Status tweet in asyncResponse.State
                                       select new TwitterItem
                                       {
                                           ImageSource=tweet.User.ProfileImageUrl,
                                           Message=tweet.Text
                                       })
                                           .ToList();
                               }));
               lstTwitter.StopPullToRefreshLoading(true);
           }
       }
 
private void txtUserName_ActionButtonTap(object sender, EventArgs e)
{
    LoadTweets();
}
 
private void lstTwitter_RefreshRequested(object sender, EventArgs e)
{
    LoadTweets();
}

We first check to see if we have authenticated properly and if we aren’t then inform the user. If we are authenticated then we are going to select the tweets with the username typed into our TextBox with an Async callback and add the results to our RadDataBoundListBox’s ItemSource property. Finally, we will turn off the Refresh loading animation from our RadDataBoundListBox.

Wrap-Up

Today, we saw just how quickly you could get up and running with a new Windows Phone 8 project by using a couple of our controls. Since we used our controls and a great open-source library, we were able to complete this project in just a couple of minutes. If you have any questions or comments, then please leave them below. You may also grab the source code for this project if you wish.

-Michael Crump (@mbcrump)

Special thanks to Lance McCarthy for his OAuth insight and Joe Mayo for reviewing the Linq2Twitter code.


MichaelCrump
About the Author

Michael Crump

is a Microsoft MVP, Pluralsight and MSDN author as well as an international speaker. He works at Telerik with a focus on everything mobile.  You can follow him on Twitter at @mbcrump or keep up with his various blogs by visiting his Telerik Blog or his Personal Blog.

Related Posts

Comments