Over the last several months, I’ve been modifying LINQ to Twitter to support multiple platforms. Originally, I had targeted full profile .NET, ASP.NET Web Forms, and ASP.NET MVC apps. An easy stop along the way was Mono compatibility, but that was simple because Mono is good about running any CLR app. The code-base was good until I started porting to Silverlight.
Porting to Silverlight
Silverlight requires a different type of class library, so right-away I couldn’t use the same libraries as the full profile version. To fix this, I moved the physical files over to the Silverlight library and tried to compile. This didn’t work because certain .NET libraries were either not present, missing features, or required additional code in Silverlight. I didn’t want to maintain two separate code bases, so I left the physical files in the Silverlight project and created file links from the full profile library to the Silverlight files. To create file links, I right-clicked the folder, selected Add Existing Files, and navigated to and selected the files. Instead of clicking the Add button, there’s a drop-down arrow on the right side of the Add button, which has an option named Add As Link, which I selected. This still doesn’t fix the problem with differences in libraries.
To account for the differences in libraries, I used pre-processing directives. Silverlight has a defined SILVERLIGHT symbol, that ships with the default project template, which is what I used. Here’s an example of how I used it:
#if SILVERLIGHT
WebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);
WebRequest.RegisterPrefix("https://", WebRequestCreator.ClientHttp);
#endif
The example above demonstrates a Silverlight-only scenario requiring registration of prefixes for HTTP communication. It uses #if and #endif to block off code that will only compile in the Silverlight project, which defines the SILVERLIGHT symbol.
A natural consequence of this strategy is that you only want to use a symbol that is unique to a specific project type if the logic only pertains to that project type. However, sometimes the lines blur. After porting to Silverlight, I went on to create a Windows Phone version of LINQ to Twitter.
Porting to Windows Phone
Since Windows Phone uses Silverlight, I was tempted to use the same define symbol, but that wouldn’t be good because there are situations, like the example above that are unique to Silverlight Web Applications, but not Silverlight for Windows Phone. Fortunately, Windows Phone has a default WINDOWS_PHONE symbol that ships with its templates. Here’s an example for a Silverlight scenario that doesn’t work for Windows Phone:
#if SILVERLIGHT && !WINDOWS_PHONE
if (!Application.Current.IsRunningOutOfBrowser)
{
ProxyUrl =
Application.Current.Host.Source.Scheme + "://" +
Application.Current.Host.Source.Host + ":" +
Application.Current.Host.Source.Port + "/LinqToTwitterProxy.ashx?url=";
}
#else
ProxyUrl = string.Empty;
#endif
In the example above, Silverlight Web Apps require a proxy, but Windows Phone doesn’t. This results in a more sophisticated condition that excludes Windows Phone’s from being configured with a proxy. Notice the AND and NOT operators and the #else clause for refining this condition.
Porting to Client Profile
After supporting Silverlight and Windows Phone, I turned my attention to a recurring problem that I saw happening. It seems that people would try out LINQ to Twitter by starting a new Console app and running a simple query. The problem is that it wasn’t so simple because the default profile of a Console application is Client Profile. The conflict occurs because LINQ to Twitter supports ASP.NET Web Forms and MVC, whose libraries are not included in Client Profile. This prevented the application from building. Most people figured out that they could move forward by opening Properties and and switching the Target framework to one of the non-Client Profile options, but the situation did highlight the usefulness of supporting Client Profile.
Client Profile doesn’t have any default defined symbols, so I created one for the new library named CLIENT_PROFILE. At first, this was very useful because I learned that Client Profile doesn’t include any of the JSON serialization libraries that I was using. Fortunately, I had recently integrated LitJson into LINQ to Twitter, which I could use with the Client Profile library. Here’s an example:
#if SILVERLIGHT || CLIENT_PROFILE
var array = dictionary.GetValue<list<object>>(key, null);
#else
var array = dictionary.GetValue<ArrayList>(key, null);
#endif
The example above uses the OR operator in the pre-processing directive to indicate that both Silverlight and Client Profile need the same code – operating on a generic List<object> because ArrayList isn’t part of their profiles.
Porting to Windows 8
Most recently, I ported LINQ to Twitter to support Windows 8 Metro Style Class Libraries. The template for Windows 8 libraries ships in Visual Studio 11 and defines the NETFX_CORE symbol. There are a few significant library changes that I had to account for, but making the code work on multiple platforms, including Windows 8 is doable. Here’s one example:
#if NETFX_CORE
Task.Delay(errorWait);
#else
Thread.Sleep(errorWait);
#endif
In Windows 8, you use the Task Parallel library (TPL), instead of the Thread class and other .NET libraries. Since LINQ to Twitter supports .NET 3.5, but Microsoft doesn’t officially support TPL for .NET 3.5, the Thread class is still necessary. I encountered more scenarios with various types, reflection, and collections that needed special handling with pre-processing directives, all of which were handled similar to the examples you’ve seen so far. Moving the code between Visual Studio 11 and Visual Studio 2010 was seamless because I didn’t change the Target frameworks on any of the other class library types.
Note: You can view the LINQ to Twitter Source Code on CodePlex to see what my check-ins looked like today (5/10/12) to see how I made the LinqToTwitterRT library changes and merged with the existing code base.
Summary
Porting class libraries to different .NET platforms isn’t always easy. Each platform adds and removes features that are appropriate in their own context. My approach was to have a common set of physical files, link to those files from other projects, and then use pre-processing directives to manage the differences. You saw examples of how I did this by porting to Silverlight, Windows Phone, Client Profile, and finally Windows 8. As you can see the code gets a bit fragmented at times, but it isn’t too bad, and most importantly, it works.
@JoeMayo
In the Developer Preview of Windows 8, Visual Studio 11 conveniently allowed references to .NET 4.0 apps. I had blogged previously on how to use LINQ to Twitter with Windows 8. Subsequently, the Consumer Preview of Windows 8 no longer allowed references to .NET libraries and requires references to Windows 8 Metro Style Application Libraries. I looked at Portable Class Libraries, but that doesn’t work because LINQ to Twitter is an IQueryable LINQ provider, which isn’t supported. So, I redirected my focus and am pleased to announce the first beta of LINQ to Twitter for Windows 8.
The download is available on CodePlex at LINQ to TWitter for Windows 8.
In addition to the new LinqToTwitterRT.dll library, the download page includes a Windows 8 Metro Application project, MetroSearchDemo, you can use to try this out. For an explanation of the code, you can view my previous Windows 8 post, which is similar.
@JoeMayo
I’m using xUnit and the Resharper test runner. Today, I ran into a situation where I couldn’t run tests. The runner icons weren’t showing in the gutter. Then I pressed Ctrl+U+R and received the following message:

Well, there were several tests in the file, decorated with FactAttribute. Considering that I the code was written via TDD and the test were definitely working, I was curious why I suddenly couldn’t run them.
It turns out that I removed the public modifier from the class in the not-so-distant past. I don’t remember doing it, but it sure was missing.
The fix was to add the public modifier back to the test class. The Resharper test runner started working immediately.
@JoeMayo
The most recent release of LINQ to Twitter included support for Windows Phone. It’s important to note that only 7.1 is supported – the rationale being that 7.1 (Mango) introduced support for IQueryable, which LINQ to Twitter requires. This post will show you how to use LINQ to Twitter with Windows Phone. You’ll see a normal public query, how to log in with OAuth, and how to post a tweet. All of the code in this blog post is included with the LINQ to Twitter source code that you can download at http://linqtotwitter.codeplex.com.
Getting Started
The first thing you’ll need to do is create a new Windows Phone project or have an existing Windows Phone project for which you would like to add Twitter integration. When the project is open, you can use NuGet to add a reference to LINQ to Twitter. Check out A Gentle Introduction to NuGet if you don’t have NuGet yet. Alternatively, you can visit the LINQ to Twitter site on CodePlex and download the Windows Phone version and create a file reference to the LinqToTwitterWP.dll assembly.
After setting up the project, the first task is to shape the data for binding to the UI.
The Model
The actual data shown on the screen is a tiny subset of what Twitter returns. Here’s PublicTweet, which is the model object to display on screen:
namespace WindowsPhoneDemo
{
public class PublicTweet
{
public string UserName { get; set; }
public string Message { get; set; }
public string ImageSource { get; set; }
}
}
The application will create a collection of PublicTweet and bind each instance to the UI, discussed in the next section.
Making a Public Tweets Query
When you create a Windows Phone application, one of the files you get is MainPage.xaml, which is the default startup page. Below is the associated MainPage.xaml.cs, which contains a button click event handler that performs a query for the public timeline, using LINQ to Twitter:
using System.Linq;
using System.Windows;
using LinqToTwitter;
using Microsoft.Phone.Controls;
namespace WindowsPhoneDemo
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
}
private void PublicTimelineButton_Click(object sender, RoutedEventArgs e)
{
var ctx = new TwitterContext();
(from tweet in ctx.Status
where tweet.Type == StatusType.Public
select tweet)
.AsyncCallback(tweets =>
Dispatcher.BeginInvoke(() =>
{
var publicTweets =
(from tweet in tweets
select new PublicTweet
{
UserName = tweet.User.Identifier.ScreenName,
Message = tweet.Text,
ImageSource = tweet.User.ProfileImageUrl
})
.ToList();
PublicTweetListBox.ItemsSource = publicTweets;
}))
.SingleOrDefault();
}
}
}
To understand the query above, remember that all Internet communication in Windows Phone must be asynchronous (async). You don’t see a return value assigned from the query because that implies a blocking call that isn’t allowed.
In LINQ to Twitter, I solved the blocking problem with an idiom that relies on an extension method named AsyncCallback. Behind the scenes, LINQ to Twitter takes care of the plumbing associated with async communication and invokes the delegate, of type Action<IEnumerable<T>>, that you pass as a parameter to AsyncCallback.
In the code above, the AsyncCallback parameter is a lambda. The tweets parameter is IEnumerable<Status> because a LINQ to Twitter Status query of type StatusType.Public returns a collection of Status entities. Since the result is IEnumerable<T>, you can use LINQ to Objects to project the Status entities in to PublicTweet model instances.
Note: Don’t forget to used Dispatcher.BeginInvoke. Invocation of AsyncCallback within LINQ to Twitter occurs on a thread other than the UI thread. Therefore, you must marshal the thread back onto the UI thread to keep your application from crashing.
The example above assigns results of the query, projected into publicTweets, to the ItemsSource property of PublicTweetListBox. Here’s the XAML from MainPage.xaml, showing you how the layout and binding for the Public Tweets query occurs:
<phone:PhoneApplicationPage
x:Class="WindowsPhoneDemo.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
shell:SystemTray.IsVisible="True">
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="LINQ to Twitter" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="Public Tweets" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}" FontSize="72" />
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Button Content="Get Public Timeline" Height="72" HorizontalAlignment="Left" Margin="51,66,0,0" Name="PublicTimelineButton" VerticalAlignment="Top" Width="365" Click="PublicTimelineButton_Click" />
<ListBox Height="465" HorizontalAlignment="Left" Margin="5,144,0,0" Name="PublicTweetListBox" VerticalAlignment="Top" Width="451">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Height="132">
<Image Source="{Binding ImageSource}" Height="73" Width="73" VerticalAlignment="Top" Margin="0,10,8,0"/>
<StackPanel Width="370">
<TextBlock Text="{Binding UserName}" Foreground="#FFC8AB14" FontSize="28" />
<TextBlock Text="{Binding Message}" TextWrapping="Wrap" FontSize="24" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<HyperlinkButton Content="Status Update" Height="30" HorizontalAlignment="Left" Margin="122,6,0,0" Name="StatusUpdateHyperlink" VerticalAlignment="Top" Width="200" NavigateUri="/StatusUpdate.xaml" />
</Grid>
</Grid>
</phone:PhoneApplicationPage>
In the XAML code above, you can see that the Button Click event is hooked up to the PublicTimeline_Click handler defined in the previous listing for the code-behind.
The DataTemplate for the ListBox specifies binding for properties exposed by the PublicTweets model.
Notice also that there’s a HyperlinkButton, providing navigation to StatusUpdate.xaml, which lets the user post a tweet. While public queries don’t require authentication, actions that occur on behalf of a user, such as posting tweets, must be authenticated, which I’ll discuss next.
Authenticating with OAuth
The Twitter API uses OAuth exclusively for authentication. There was a time when username/password authentication was supported, but proved to have too many security weaknesses which isn’t appropriate as a generalized solution for Web application communication scenarios. Fortunately, LINQ to Twitter supports OAuth organically.
Tip: For more information on how LINQ to Twitter supports OAuth and additional references, you can visit the documentation pages on Securing Your Applications.
In this example, I’ll check to see if the user is authenticated before allowing them to tweet. Here’s an excerpt from StatusUpdate.xaml.cs, the code behind for the Status Update page that allows you to tweet. It’s the button click handler that performs the tweet. What you see is the code that checks if the user is authenticated. I’ll show the actual tweet logic in the next section, but we’ll focus right now on the authentication logic:
private void TweetButton_Click(object sender, RoutedEventArgs e)
{
if (string.IsNullOrWhiteSpace(TweetTextBox.Text))
{
MessageBox.Show("Please enter text to tweet.");
}
ITwitterAuthorizer auth = SharedState.Authorizer;
if (auth == null || !auth.IsAuthorized)
{
NavigationService.Navigate(new Uri("/OAuth.xaml", UriKind.Relative));
}
else
{
// UpdateStatus showing how to post a tweet omitted
// - delayed until next section of this blog post
}
}
After making sure the user typed some text, the code above assigns a reference to the application’s ITwitterAuthorizer, auth, which is an instance of a LINQ to Twitter type that manages OAuth. SharedState is a static class that facilitates sharing the ITwitterAuthorizer between pages of the application, shown below:
using LinqToTwitter;
namespace WindowsPhoneDemo
{
public static class SharedState
{
public static ITwitterAuthorizer Authorizer { get; set; }
}
}
Looking back at the previous code, with the TweetButton_Click handler, notice that after checking that auth isn’t null, I call IsAuthenticated to see if the user authenticated yet. If false, the application navigates to OAuth.xaml for authentication.
Tip: At this point, you could also call your own business object that can instantiate and load credentials (that were saved previously) for the ITwitterAuthorizer. This post shows how to instantiate the ITwitterAuthorizer and you can build upon that knowledge to make your application more flexible.
The code-behind in OAuth.xaml.cs contains methods to guide the authentication process. It sets up the proper events for the page, begins the authorization process, and handles completion of the authorization process. The application uses Twitter’s PIN OAuth authorization process that includes the following steps: request authorization, get a pin number, submit the pin back to Twitter, and then receive authentication credentials for working with Twitter. Here’s the code:
using System;
using System.Windows;
using System.Windows.Navigation;
using LinqToTwitter;
using Microsoft.Phone.Controls;
namespace WindowsPhoneDemo
{
public partial class OAuth : PhoneApplicationPage
{
PinAuthorizer pinAuth;
public OAuth()
{
InitializeComponent();
Loaded += Page_Loaded;
OAuthWebBrowser.LoadCompleted += OAuthWebBrowser_LoadCompleted;
}
void OAuthWebBrowser_LoadCompleted(object sender, NavigationEventArgs e)
{
EnterPinTextBlock.Visibility = Visibility.Visible;
PinTextBox.IsEnabled = true;
AuthenticateButton.IsEnabled = true;
}
void Page_Loaded(object sender, RoutedEventArgs e)
{
pinAuth = new PinAuthorizer
{
Credentials = new InMemoryCredentials
{
ConsumerKey = "",
ConsumerSecret = ""
},
UseCompression = true,
GoToTwitterAuthorization = pageLink =>
Dispatcher.BeginInvoke(() => OAuthWebBrowser.Navigate(new Uri(pageLink, UriKind.Absolute)))
};
pinAuth.BeginAuthorize(resp =>
Dispatcher.BeginInvoke(() =>
{
switch (resp.Status)
{
case TwitterErrorStatus.Success:
break;
case TwitterErrorStatus.TwitterApiError:
case TwitterErrorStatus.RequestProcessingException:
MessageBox.Show(
resp.Error.ToString(),
resp.Message,
MessageBoxButton.OK);
break;
}
}));
}
private void AuthenticateButton_Click(object sender, RoutedEventArgs e)
{
if (string.IsNullOrEmpty(PinTextBox.Text))
{
MessageBox.Show(
"Input Error",
"Please enter PIN",
MessageBoxButton.OK);
return;
}
pinAuth.CompleteAuthorize(
PinTextBox.Text,
completeResp => Dispatcher.BeginInvoke(() =>
{
switch (completeResp.Status)
{
case TwitterErrorStatus.Success:
SharedState.Authorizer = pinAuth;
NavigationService.GoBack();
break;
case TwitterErrorStatus.TwitterApiError:
case TwitterErrorStatus.RequestProcessingException:
MessageBox.Show(
completeResp.Error.ToString(),
completeResp.Message,
MessageBoxButton.OK);
break;
}
}));
}
}
}
At the top of the listing, you see a PinAuthorizer field, pinAuth, which is type ITwitterAuthorizer and will be accessed via methods that begin and complete the authentication processs. The constructor adds handlers for Loaded and LoadCompleted events of the Page and WebBrowser, respectively.
- The page has a WebBrowser control for user interaction with the OAuth authentication process and we can’t operate on that control properly until its LoadCompleted event. The sequence of methods works like this:
- As soon as the program navigates to OAuth.xaml, the Page_Load handler begins the authentication process.
- The user will authorize the application and receive a pin that displays in the WebBrowser.
- The OAuthWebBrowser_LoadCompleted handler enables the TextBox where the user types the pin and turns on the button so the user can complete the authorization process.
- The AuthenticateButton_Click handler executes (when the user clicks AuthenticateButton).
- The code completes the authentication process, and the user is redirected back to the StatusUpdate.xaml page.
As mentioned previously, the whole process kicks off via the Page_Load method. You can see how the new PinAuthorizer is instantiated with a new Credentials instance. In this example, credentials are empty and you must write the code that populates ConsumerKey and ConsumerSecret properties. The GoToTwitterAuthorization is an Action<string> that allows an application to navigate to Twitter’s authentication Web page after the request is initialized.
Note: Having a solid grasp of the OAuth authentication process will reduce much confusion. The amount of information for explaining the process is beyond the scope of this post, but is documented on the LINQ to Twitter site under Securing Your Applications.
Call BeginAuthorize on the ITwitterAuthorizer, pinAuth, to begin the authentication process. Since this requires async communication, the parameter is an Action<TwitterAsyncResponse<object>>. TwitterAsyncResponse is a LINQ to Twitter type that makes it easy for you to process results from Twitter. The TwitterErrorStatus enum helps you discern between causes of error or success during communication.
Tip: Since errors communicating with Twitter are common, best practice is to use TwitterErrorStatus for proper error handling.
Calling Dispatcher.BeginInvoke marshals the operation back onto the UI thread.
Reminder: As mentioned earlier, async responses from LINQ to Twitter occur on their own thread, so you’ll want to marshal operations back onto the UI thread as I did with Dispatcher.BeginInvoke.
As discussed earlier, after the authentication process begins and the user is authenticated, the user will enter a PIN in the PinTextBox and click AuthenticateButton. This invokes the AuthenticateButton_Click event handler, in the code above, executing the completion process.
When calling CompeteAuthorize on the ITwitterAuthorizer, pinAuth, pass the pin from PinTextBox and add a callback handler for the Twitter response. The second parameter for CompleteAuthorize is Action<TwitterAsyncResponse<UserIdentifier>>. In the call to BeginAuthorize, the TwitterAsyncResponse type parameter was object because it wasn’t used, but is UserIdentifier in CompleteAuthorize. The TwitterAsyncResponse type parameter defines the type returned in the Status property of the result, which is completeResp.Status in this case. This allows you to read ScreenName or UserID returned from Twitter if you need it. i.e. completeResp.Status.ScreenName.
Notice that the TwitterErrorStatus.Success case assigns pinAuth to SharedState.Authorizer so it’s accessible to the rest of the program. Then it goes back to the previous page, StatusUpdate.xaml, which is discussed next.
Posting a Tweet
Now that you’re authorized, you can tweet. This involves using the LINQ to Twitter UpdateStatus method, shown below:
using System;
using System.Globalization;
using System.Windows;
using LinqToTwitter;
using Microsoft.Phone.Controls;
namespace WindowsPhoneDemo
{
public partial class StatusUpdate : PhoneApplicationPage
{
public StatusUpdate()
{
InitializeComponent();
TweetTextBox.Text = "Windows Phone Test, " + DateTime.Now.ToString(CultureInfo.InvariantCulture) + " #linq2twitter";
}
private void TweetButton_Click(object sender, RoutedEventArgs e)
{
if (string.IsNullOrWhiteSpace(TweetTextBox.Text))
{
MessageBox.Show("Please enter text to tweet.");
return;
}
ITwitterAuthorizer auth = SharedState.Authorizer;
if (auth == null || !auth.IsAuthorized)
{
NavigationService.Navigate(new Uri("/OAuth.xaml", UriKind.Relative));
}
else
{
var twitterCtx = new TwitterContext(auth);
twitterCtx.UpdateStatus(TweetTextBox.Text,
updateResp => Dispatcher.BeginInvoke(() =>
{
switch (updateResp.Status)
{
case TwitterErrorStatus.Success:
Status tweet = updateResp.State;
User user = tweet.User;
UserIdentifier id = user.Identifier;
MessageBox.Show(
"User: " + id.ScreenName +
", Posted Status: " + tweet.Text,
"Update Successfully Posted.",
MessageBoxButton.OK);
break;
case TwitterErrorStatus.TwitterApiError:
case TwitterErrorStatus.RequestProcessingException:
MessageBox.Show(
updateResp.Error.ToString(),
updateResp.Message,
MessageBoxButton.OK);
break;
}
}));
}
}
}
}
You saw the first part of the TweetButton_Click handler earlier when I explained how to begin the authentication process. Now look at the else clause that executes when authentication succeeds. To use the authentication credentials, pass the ITwitterAuthorizer instance, auth, to the TwitterContext constructor.
UpdateStatus is a method you can call through the TwitterContext instance, twitterCtx, to tweet. The first parameter is the text to tweet and the second parameter is an Action<TwitterAsyncResponse<Status>>. The lambda calls Dispatcher.BeginInvoke to marshal the operation back onto the UI thread.
Reminder: As mentioned earlier, async responses from LINQ to Twitter occur on their own thread, so you’ll want to marshal operations back onto the UI thread as I did with Dispatcher.BeginInvoke.
The updateResp parameter contains the result, which is a TwitterAsyncResponse<Status>. You can see in the TwitterErrorStatus.Success case of the switch statement where updateResp.Status is type Status, which is specified as the TwitterAsyncResponse type parameter. Here’s the XAML from StatusUpdate.xaml:
<phone:PhoneApplicationPage
x:Class="WindowsPhoneDemo.StatusUpdate"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
SupportedOrientations="Portrait" Orientation="Portrait"
mc:Ignorable="d" d:DesignHeight="768" d:DesignWidth="480"
shell:SystemTray.IsVisible="True">
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!--TitlePanel contains the name of the application and page title-->
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock x:Name="ApplicationTitle" Text="LINQ to Twitter" Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock x:Name="PageTitle" Text="Status Update" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<!--ContentPanel - place additional content here-->
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Button Content="Tweet" Height="72" HorizontalAlignment="Left" Margin="143,127,0,0" Name="TweetButton" VerticalAlignment="Top" Width="160" Click="TweetButton_Click" />
<TextBox Height="72" HorizontalAlignment="Left" Margin="0,49,0,0" Name="TweetTextBox" Text="" VerticalAlignment="Top" Width="467" />
<HyperlinkButton Content="Public Timeline" Height="30" HorizontalAlignment="Left" Margin="119,6,0,0" Name="hyperlinkButton1" VerticalAlignment="Top" Width="200" NavigateUri="/MainPage.xaml" />
</Grid>
</Grid>
</phone:PhoneApplicationPage>
The listing above shows that the screen has a TextBox for tweet input, a button for initiating the tweet, and a HyperlinkButton that allows navigation back to the Public Query page.
Summary
After learning how to get started with using LINQ to Twitter on a new Windows Phone project, you saw how public queries work. The post followed up with an explanation of how to use LINQ to Twitter’s built-in OAuth authentication services, which was required for the subsequent explanation of how to post a tweet. You also learned how to use LINQ to Twitter’s async idioms and how to manage callbacks and the data returned.
@JoeMayo
One of the new data controls in Windows 8 Metro is the ListView. The ListView does the same thing as the ListBox, plus more. In this post, I’ll build on the TwitterClient, from my previous post: Windows 8 Composition and Content. and show how to refactor the ListBox to a ListView. I’ll also mention a few of the differences between the two controls.
Refactor ListBox to ListView
To save you a little time, I’ll show you the XAML for the ListBox, from my previous post. Then I’ll follow up with changes for making that work as a ListView. Here’s the code for the ListBox:
<ListBox Height="465" HorizontalAlignment="Left" Margin="5,144,0,0"
Name="PublicTweetListBox" VerticalAlignment="Top" Width="1355"
ItemsSource="{Binding Tweets}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Height="132">
<Button>
<Image Source="{Binding ImageUrl}"
Height="73" Width="73"
VerticalAlignment="Top" Margin="0,10,8,0"/>
</Button>
<StackPanel Width="370">
<TextBlock Text="{Binding Name}"
Foreground="#FFC8AB14" FontSize="28" />
<TextBlock Text="{Binding Text}"
TextWrapping="Wrap" FontSize="24" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
If you’ve seen the previous post, the code above isn’t anything different – it’s a ListBox with a DataTemplate and bindings to a ViewModel. Here’s how to change the code to switch this to a ListView:
<ListView Height="465" HorizontalAlignment="Left" Margin="5,144,0,0"
Name="PublicTweetListView" VerticalAlignment="Top" Width="1355"
ItemsSource="{Binding Tweets}">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Height="132">
<Button>
<Image Source="{Binding ImageUrl}"
Height="73" Width="73"
VerticalAlignment="Top" Margin="0,10,8,0"/>
</Button>
<StackPanel Width="370">
<TextBlock Text="{Binding Name}"
Foreground="#FFC8AB14" FontSize="28" />
<TextBlock Text="{Binding Text}"
TextWrapping="Wrap" FontSize="24" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
No need to rub your eyes, all that’s required to change from a ListBox to a ListView is to change all the tag names that say ListBox to ListView. Besides a name, there’s more that changes, which I’ll discuss next.
Advantages of ListView over ListBox
The biggest advantage of leaving ListBox in Metro is for backwards compatibility with existing XAML app platforms. However, moving to the new Windows 8 data controls like ListView, GridView, etc. give you some advantages. Windows 8 data controls have inherent support for the type of visual feedback associated with touch apps. For example, a feature called snap grid causes the list to reposition a list item into view if you stopped panning when that list item is not fully in view. Another feature is inertia, where the grid keeps scrolling based on the speed of the pan.
Note: The new data/list controls have built-in behaviors, such as snap grid and inertia that are based on animations.
In addition to the visual feedback provided by the new Windows 8 controls, you also have more functionality exposed through the control’s APIs. The ListView control derives from a new class, ListViewBase, and both ListViewBase and ListBox derive from Selector:
Selector
ListBox
ListViewBase
GridView
ListView
Through ListViewBase, ListView gets new events, methods, and properties that help it provide the built-in support for Metro look and feel.
By moving from ListBox to ListView, you essentially get all this new functionality for free. On top of that, you have API support to customize that behavior as you need.
Summary
You saw how easy it is to convert from ListBox to ListView. I followed up with a few comments about the benefits of ListView over ListBox, explaining how ListView gives you all the new Metro look and feel behaviors for free.
@JoeMayo
Composition is an integral part of Windows 8 UI design from both aesthetic and logical perspectives. This post modified my previous post, Refactoring Windows 8 Code-Behind to MVVM. adding to the variety of compositional examples. I’ll start with an explanation of composition in Windows 8, modify the previous code to show the power of composition, and then highlight a few more existing examples of where composition naturally fits into the Windows 8 UI environment.
Understanding Windows 8 Composition
A Windows 8 UI is built like a tree. You have a single root element that surrounds all other elements, multiple branches containing more elements, and finally many leaves that don’t contain any elements. In shorthand, the structure looks something like this:
Root
Content
Branch
Branch
Leaf
Branch
Leaf
Leaf
Branch
Leaf
You might have noticed that I sneaked in an extra element, Content, in the figure above that I hadn’t talked about yet. Nevertheless, Content is necessary and important in Windows 8 development. The figure above is a generalization of the hierarchical relationship between elements. However, the XAML below, based on the previous post, is a concrete example:
<UserControl x:Class="TwitterClient.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:DesignHeight="768" d:DesignWidth="1366">
<Grid x:Name="LayoutRoot" Background="#FF0C0C0C">
<Button Content="Refresh Public Tweets" Height="72" Width="365"
HorizontalAlignment="Left" Margin="500,66,0,0"
Name="RefreshButton" VerticalAlignment="Top"
Command="{Binding RefreshCommand}"/>
<ListBox Height="465" HorizontalAlignment="Left" Margin="5,144,0,0"
Name="PublicTweetListBox" VerticalAlignment="Top" Width="1355"
ItemsSource="{Binding Tweets}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Height="132">
<Image Source="{Binding ImageUrl}"
Height="73" Width="73"
VerticalAlignment="Top" Margin="0,10,8,0"/>
<StackPanel Width="370">
<TextBlock Text="{Binding Name}"
Foreground="#FFC8AB14" FontSize="28" />
<TextBlock Text="{Binding Text}"
TextWrapping="Wrap" FontSize="24" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</UserControl>
The example above gives a better idea of the compositional relationship between elements and how they form a tree that is visually identifiable through proper spacing of elements. UserControl is the Root element and Grid is the Content element for Root. Subsequent elements form a hierarchy, further displaying the compositional nature of Windows 8 UI development.
Since the examples in this post are based on the previous post, you might find it useful to have a few tips on getting from there to here, which is discussed next.
Reusing Previous Code
Over the past couple of posts, I’ve renamed the same project to something new. This is more tedious than necessary, so I’ll just rename the project one more time to something more generic, like TwitterClient. If you’re thinking, “Oh no, not another Twitter client!”, don’t worry. It’s just a sample program – and besides, no one will ever use it.
Here’s a quick walk-through of the file system part of the rename:
- Make a copy of RefactorToMVVM folder in Windows Explorer and rename it to TwitterClient.
- In the new TwitterClient folder, rename the solution file, RefactorToMVVM.sln, to TwitterClient.sln.
- Unhide files and rename RefactorToMVVM.v11.suo to TwitterClient.v11.suo (Alternatively delete because VS11 recreates it for you).
- Rename the project folder, RefactorToMVVM, to TwitterClient.
- In the new TwitterClient project folder, rename the project file, RefactorToMVVM.csproj, to TwitterClient.csproj.
Now your file names are up-to-date, you’ll need to change a couple more items in the solution. To get started on this part, go back to the TwitterClient solution folder and double-click on TwitterClient.sln to open the solution. You’ll see an error saying that VS can’t open the RefactorToMVVM project and that’s okay because you intentionally renamed it – meaning that the solution file won’t be able to find the project file under it’s new name. Click OK for the error message box that appears. The following steps fix the project load problem and take you through the rest of the renaming:
- After the solution loads, right-click on the grayed-out RefactorToMVVM project and select Remove.
- Right-click on the solution, select Add, Existing Project and an Add Existing Project window will appear.
- Navigate to the TwitterClient solution, down to the TwitterClient project, select TwitterClient.csproj and click OK. The new project will load.
- Under the TwitterClient project, double-click Properties to open the Properties configuration page.
- On the Properties Application tab, change both the Assembly name and Default namespaces to TwitterClient.
- Open Tweet.cs (or any code file), select RefactorToMVVM, type Ctrl+R+R, and rename to TwitterClient. Select preview, comments, and strings options and observe all the places in code where the change is made. Click Apply when you’re ready to make the changes.
- Double-click the Package.appxmanifest file, which opens the Package configuration window.
- On the Application UI tab, change Display Name to TwitterClient, Entry Point to TwitterClient.App, and Description to Client Application for Twitter.
- On the Packaging tab, change Package Display Name to TwitterClient.
- Save and close Package.appxmanifest.
- The visual designer for Package.appxmanifest doesn’t let you change everything and there’s one more item to remember. Right-click on Package.appxmanifest, select Open With, select XML Editor, and click OK.
- Under /Applications/Application, change the Executable attribute to TwitterClient.exe.
Before finishing, press F7 to build the solution. If you have errors, it’s most likely because of the naming changes done previously. So, it would be useful to retrace your steps if the error message doesn’t lead you to the answer right away. Now that we have a new renamed solution/project, we can proceed to an in-depth discussion of Composition and Content by adding a button the the tweet list.
Adding a Button
Here, we’re not going to just add a button, we’re going to examine how a button supports composition through its Content property. You’ll see attribute content, element content, and a cool trick that makes it easy to code compositional content in XAML.
If you want a simple button with text, you can use the Content attribute, like this:
<Button Content="{Binding Name}" />
The XAML Content attribute corresponds to a Content property of the Button class. Your first thought, upon seeing the Content property on a Button, might be to ask, “Why isn’t this property named Text?” That’s a logical question, especially if you’ve been using Windows Forms, ASP.NET, or one of many other UI frameworks. Actually, Windows 8 is closer to both Silverlight and WPF in their view of composition and content.
The primary rationale for content is because text isn’t the only object you can display on a button. You can add different types of UI elements to a button by assigning those items to the Content property. In previous frameworks, that don’t support content, you would have needed to slog through extra code to create a special button. With Windows 8, you only need to assign a value to the content property of a given control. Here’s an example for creating a button that contains an image:
<Button>
<Button.Content>
<Image Source="{Binding ImageUrl}"
Height="73" Width="73"
VerticalAlignment="Top" Margin="0,10,8,0"/>
</Button.Content>
</Button>
Above, Button contains an image, which can’t be represented in text, as previously shown via the Content attribute. This example uses Property Element syntax – which is the control type and property name, separated by a dot. The power of this approach to re-defining the appearance of a button can’t be understated – you can see how easy it is to do.
Note: The content property isn’t always named Content. i.e. Types derived from ItemsControl, such as ListBox designate the Items property as their content property.
A control can be decorated with Windows.UI.Xaml.Markup.ContentPropertyAttribute, specifying what the content property is for that control. In the case of Button, the content property is Content (same name):
[ContentProperty("Content")]
public class UserControl : Windows.UI.Xaml.Controls.Control
{
// ...
public UIElement Content { get; set; }
// ...
}
This is good information if you’re a control developer, but it’s also interesting because of a special feature of content properties that gives you simpler syntax. More specifically, you can remove the Property Element syntax, like this:
<Button>
<Image Source="{Binding ImageUrl}"
Height="73" Width="73"
VerticalAlignment="Top" Margin="0,10,8,0"/>
</Button>
The image below is a new snapshot of the updated screen, showing how the images look as buttons. As you can see, customizing buttons is very easy. More to the point, composing custom UI elements is easy via Windows 8 content support.

While this discussion focused on the Button, many other control types have content properties and support composition the same way. If you look back at the XAML in the previous section, “Understanding Windows 8 Composition”, you’ll see several more composition examples, including UserControl/Grid, Grid/Elements, ListBox/ListBox.ItemTemplate, and so on.
Summary
This post demonstrated the inherent support for composition in Windows 8 UI development. This capability is supported via content properties. You saw how Button demonstrates the power of composition and the role of the content property in facilitating composition. Remember that Button is only an example, and you should understand that other controls have content properties.
@JoeMayo
In my previous post, Using LINQ to Twitter in Windows 8 Metro Apps, I cheated a little (some might say a lot) on my UI architecture by using code-behind. In this post, I’ll make it all better by showing you how to separate the model and interaction logic from the UI design – proper separation of concerns.
I’ll accomplish this with a pattern, named Model-View-ViewModel (MVVM), which is widely used for WPF, Silverlight, and (soon) Windows 8 Metro Apps. I’ll start by discussing what MVVM is, move to how I’ll apply it to the previous Windows 8 Metro app, and finish with a step-by-step walkthrough to refactor from code-behind to MVVM.
Understanding MVVM
The subject of whether to use MVVM or not can be debated forever. However, it’s a useful way to achieve separation of concerns in your application and many people like and use it, including myself.
Jeremy Likeness has a nice site that specializes in the subject: MVVM Explained.
Designing Our Implementation
There are a handful of good frameworks for helping you write applications using MVVM. In this app, Since Windows 8 is so new, these frameworks aren’t generally available or ready. However, MVVM is a pattern, not a library, and you can always provide your own code to support the pattern, as you’ll see in this post.
This application will work exactly the same as the original, displaying public tweets when a button is clicked, but the internal implementation will be modified. In particular, the classes and relationship between classes are altered to match the MVVM pattern. The following illustration shows this relationship:

The three objects in the illustration above represent files for implementing a View, ViewModel, and Model. The view is MainPage.xaml, where you can see tweets and click the Refresh button. The model is an object that holds information for a single tweet. Actually, we’ll be working with a list of tweets, which will be held in the ViewModel and bound to the View.
In some diagrams, you’ll see a binding layer between the ViewModel and View, which is an important part of their relationship. In fact the binding relationship can be involved, but this application is so simple that I’ve also opted for a simpler diagram. Besides managing the model and supporting data binding, the ViewModel is instrumental in holding the current state of the view. i.e. if you select a ComboBox option, it’s the View that holds onto the value that is selected. Here’s a breakdown in responsibilities for this app:
- Model: Hold data for a single tweet. Technically, the list of tweets, held by the ViewModel is also a model component – instead of a single instance it’s a collection of instances.
- ViewModel: Hold a list of current tweets and provide a command handler that responds to Refresh button clicks and populates the list of tweets.
- View: Display tweets and let the user click a refresh button.
Refactoring the Model
In the previous post, I named the object bound to the View with a ViewModel suffix, TweetViewModel. To fix this, select the TweetViewModel.cs file, in the Solution Explorer Project, press F2 and change the name to Tweet.cs. You’ll see a message box asking if you want to do a rename and you should click the Yes button, which renames the class name in the file as well as any declarations of that class in the project.
Next, rename the Tweet property, of the Tweet class by selecting the property name, Tweet, press Ctrl+R+R, change Tweet to Text in the New name box of the Rename message box that appears, and click OK. Here’s the updated Tweet class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RefactorToMVVM
{
public class Tweet
{
public string Name { get; set; }
public string Text { get; set; }
public string ImageUrl { get; set; }
}
}
Note: I’ve also done a refactoring of the namespace, LinqToTwitterPublicQuery, to RefactorToMVVM.
Though this class was previously called a ViewModel, the name didn’t capture the essence of what a ViewModel is about: model access, binding, and state management. You’ll see some of this in the next section.
Creating the ViewModel
The ViewModel is often described as “A model of the View”, which is a non-visual abstraction of the view. The ViewModel supports separation of concerns where the concern of designing a UI occurs in the XAML, but the concern of state management and responding to events belongs to the ViewModel. In this simple ViewModel, we’ll add just enough functionality to be architecturally correct, but no more than is needed for this application. More specifically, we’ll create the PublicTweetsViewModel, shown below, that references a model and responds to refresh commands from the View (remember to add a project reference to LinqToTwitter.dll):
using System.Collections.Generic;
using System.Linq;
using LinqToTwitter;
using Windows.UI.Xaml.Data;
namespace RefactorToMVVM
{
public class PublicTweetViewModel : INotifyPropertyChanged
{
public List<Tweet> Tweets { get; set; }
public PublicTweetViewModel()
{
RefreshCommand = new TwitterCommand<object>(OnRefresh);
}
public TwitterCommand<object> RefreshCommand { get; set; }
void OnRefresh(object obj)
{
var twitterCtx = new TwitterContext();
Tweets =
(from tweet in twitterCtx.Status
where tweet.Type == StatusType.Public
select new Tweet
{
Name = tweet.User.Name,
Text = tweet.Text,
ImageUrl = tweet.User.ProfileImageUrl
})
.ToList();
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Tweets"));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
The code above has a constructor, Tweets collection property, RefreshCommand property, OnRefresh method, and PropertyChanged event. The Tweets collection will hold a list of public tweets and is populated by the OnRefresh method. Tracing back, the constructor adds the OnRefresh method as a handler for the RefreshCommand property, using the TwitterCommand, which is a special implementation of ICommand. Here’s the implementation of TwitterCommand, which you should add to another file, named TwitterCommand.cs:
using System;
using Windows.UI.Xaml.Input;
namespace RefactorToMVVM
{
public class TwitterCommand<T> : ICommand
{
readonly Action<T> callback;
public TwitterCommand(Action<T> handler)
{
callback = handler;
}
public bool CanExecute(object parameter)
{
return true;
}
public event Windows.UI.Xaml.EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
if (callback != null) callback((T)parameter);
}
}
}
The TwitterCommand constructor accepts an Action delegate, assigning handler to callback. When the View triggers the RefreshCommand in PublicTweetViewModel, Execute is invoked, which then invokes the callback delegate that the PublicTweetViewModel constructor assigned to the OnRefresh method.
When OnRefresh executes, it isn’t enough to just assign results to Tweets, you must also let the View know it should display the new data. This is where the INotifyPropertyChanged interface helps. The PropertyChanged event is a member of INotifyPropertyChanged and the View listens to this event. The following code is a snippet of PublicTweeViewModel, shown previously, with only the INotifyPropertyChanged related code:
...
public class PublicTweetViewModel : INotifyPropertyChanged
{
...
void OnRefresh(object obj)
{
...
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Tweets"));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
After LINQ to Twitter gets new tweets, OnRefresh fires the PropertyChanged event, passing the property name, Tweets, that changed. This tells the View to re-bind to Tweets.
With the ViewModel in place, all that’s left to do is hook up the ViewModel in the View and complete binding so the View doesn’t use code-behind anymore.
Binding the ViewModel to the View
The first View related task is to fix the code-behind problem. Essentially, remove all unnecessary code from MainPage.xaml.cs. So, you can delete the entire RefreshButton_Click method and set the DataContext for the View, like this:
namespace RefactorToMVVM
{
partial class MainPage
{
public MainPage()
{
InitializeComponent();
DataContext = new PublicTweetViewModel();
}
}
}
Notice how the MainPage constructor sets its DataContext property to an instance of PublicTweetViewModel. I won’t put any more code in the code-behind.
Note: I could have avoided putting any extra code in the code-behind by setting the DataContext in XAML. Unfortunately, the preview version of VS11 doesn’t support that yet. If you do, you’ll see a message like “Method 'add_PropertyChanged' in type 'RefactorToMVVM.PublicTweetViewModel' from assembly 'refactortomvvm.intermediate, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' does not have an implementation. C:\Users\jmayo\Documents\Visual Studio 11\Projects\RefactorToMVVM\RefactorToMVVM\MainPage.xaml RefactorToMVVM”.
Now, all the binding expressions in MainPage.xaml can reference properties of PublicTweetViewModel. This includes binding RefreshButton and PublicTweetListBox, like this:
<UserControl x:Class="RefactorToMVVM.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:DesignHeight="768" d:DesignWidth="1366">
<Grid x:Name="LayoutRoot" Background="#FF0C0C0C">
<Button Content="Refresh Public Tweets" Height="72" Width="365"
HorizontalAlignment="Left" Margin="500,66,0,0"
Name="RefreshButton" VerticalAlignment="Top"
Command="{Binding RefreshCommand}"/>
<ListBox Height="465" HorizontalAlignment="Left" Margin="5,144,0,0"
Name="PublicTweetListBox" VerticalAlignment="Top" Width="1355"
ItemsSource="{Binding Tweets}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Height="132">
<Image Source="{Binding ImageUrl}"
Height="73" Width="73"
VerticalAlignment="Top" Margin="0,10,8,0"/>
<StackPanel Width="370">
<TextBlock Text="{Binding Name}"
Foreground="#FFC8AB14" FontSize="28" />
<TextBlock Text="{Binding Text}"
TextWrapping="Wrap" FontSize="24" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</UserControl>
For RefreshButton, remove the Click event handler and replace it with the command binding shown above. This is how the RefreshCommand property in the PublicTweetViewModel, which is an instance of TwitterCommand binds to the button.
Since we already deleted the RefreshButton_Click method from the code behind, we need to tell PublicTweetListBox to get it’s data by binding the Tweets collection, from PublicTweetViewModel, to the ItemsSource property.
Within the DataTemplate for PublicTweetsListBox, each individual tweet binds the same as the previous post. The exception is that you must change the TextBlock binding for the previously named property, Tweet, to Text. If you recall, we changed the Tweet property of the model (also named Tweet) to Text.
That’s it, press F5 to run the application. You’ll notice that it works exactly like the previous application where pressing the Refresh Public Tweets button will load public tweets to the screen.
Summary
In this post, I attempted to redeem myself from the supposed crimes of those who would be offended. Seriously, the MVVM pattern is pretty slick in how it relies primarily on binding and keeps the UI design separate from the implementation. You saw an image of how the previous code would be refactored to support MVVM. Then I took you through a series of steps that refactored the Model, created a new ViewModel and an ICommand implementation. Finally, you learned how to connect the ViewModel to the View and bind the ICommand to the Button and data to a ListBox. The result is an application that works the same as its code-behind predecessor, yet is more maintainable because of the clean separation of concerns that MVVM helps with.
@JoeMayo
While the title of this post suggests focus on LINQ to Twitter, it also indicates that I’ll be discussing how to build a Windows 8 Metro application. The application itself will display a list of tweets from Twitter’s public feed. In the sections that follow, you’ll read background information on pre-requisites to understanding the post, learn how to get LINQ to Twitter working with Visual Studio 11, and then see a step-by-step on how the application is built.
Getting Started
You can build Metro applications with various languages, including C#, C++, JavaScript, and VB. This example uses C#. This post doesn’t dive into the gory details of how this works, but stays at the application level to hit the singular goal of building a simple application. You can visit the MSDN Windows developer center for more details.
The development model for Metro is similar to WPF or Silverlight. The user interface (UI) is built with XAML with a startup App.xaml and MainPage.xaml and associated files. If you haven’t worked with WPF or Silverlight, it would be helpful for you to learn some basic XAML, which you can find with a quick Web (Bing, Google, etc.) search. I’ll be describing the application in terms of XAML, rather than visual designer interaction. If you need a quick intro to C#, check out C# Station.
You’ll also need to install Windows 8 and Visual Studio 11 (VS11), again visiting MSDN Windows developer center for more details for more information.
Note: The “11” in Visual Studio 11 isn’t the year. The version # for Visual Studio is #11 and the beta preview is named Visual Studio 11. This could be confusing because the previous version was #10 and named Visual Studio 2010.
Setting up LINQ to Twitter
LINQ to Twitter works seamlessly with Windows 8 Metro applications, without recompilation. This means that you can visit the LINQ to Twitter download page at CodePlex.com and get the latest version. Since Visual Studio 11 works with the .NET 4.0 (v4.0.30319 as of the preview), you should download the version labeled “LINQ to Twitter .NET 4.0 Binaries“.
Creating the Project
After you open VS11, press Ctrl+Shift+N and you’ll see the following New Project window:

From the New Project window, select Visual C# > Windows Metro Style from the tree view on the left. You have various application types to choose from and each is interesting for learning some basic layout techniques. This post doesn’t cover all those features because I want to show you something simpler. So, select Application from the list and name the file LinqToTwitterPublicQuery. VS creates a new project that looks like this:

After the VS creates the application, you’ll see a new file in the designer and new projects in Solution Explorer. The file, MainPage.xaml, is the default first page to show when your application starts. To keep things simple, we’ll work on MainPage.xaml to display public tweets.
In Solution Explorer, the LinqToTwitterPublicQuery project has various folders and files. The Properties, and References folders serve the same purpose as other .NET project types. The Images folder contains default images for logos and splash screen. You can replace these images with your own. The App.xaml file contains initialization logic/markup to start the application, but we won’t be looking at it in this post, accepting whatever it’s defaults are. The Package.appxmanifest file contains XML formatted configuration information for the application. Double-clicking Package.appxmanifest opens a visual designer that makes it easy to change these parameters, but again we’ll take the defaults. Our primary focus is MainPage.xaml, which I discuss next.
Examining MainPage.xaml
MainPage.xaml is the surface upon which our UI will be built. VS provides a visual designer, giving you drag and drop capabilities to quickly populate the screen with controls. There’s also a more sophisticated UI tool, Blend, that lets you build UI’s. These are nice tools, but the XAML for this application is simple and it’s very useful to be able to work with it, so that’s what I’ll use. Here’s the XAML for MainPage.xaml:
<UserControl x:Class="LinqToTwitterPublicQuery.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:DesignHeight="768" d:DesignWidth="1366">
<Grid x:Name="LayoutRoot" Background="#FF0C0C0C">
</Grid>
</UserControl>
If you’re familiar with XML, you’ll notice that the XAML above is XML. Really, it’s a special type of XML used for building UI’s in WPF, Silverlight, and now Windows8. As described by the outer tag, MainPage.xaml is a UserControl. The namespaces are normal for supporting XAML UIs and integration with external tools, such as Blend. You can also see that the width and height are specified as attributes of the UserControl tag, after namespace declarations. The Grid is a layout control that works well for specifying rows and columns. You can change the Background attribute from nearly black, but the darker backgrounds save power, which might be appreciated even more on mobile devices, such as tablets.
Note: XAML is also used in non-UI applications, such as Windows Workflow, but for our purposes here, we’re primarily interested in using it to build UIs.
Peeking at the MainPage.xaml.cs Code-Behind
In addition to XAML, MainPage has a code-behind file, named MainPage.xaml.cs. You can open the code-behind by opening the tree branch by MainPage.xaml in the project. Here’s the code from the code-behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;
namespace LinqToTwitterPublicQuery
{
partial class MainPage
{
public MainPage()
{
InitializeComponent();
}
}
}
The relationship between the MainPage class above and the XAML is that they are partial types of the same class. The syntax in the XAML that indicates its matching partial is the x:Class attribute of the UserControl tag. When you build your project, the XAML transforms to C# code with a partial name of MainPage, as specified by the x:Class attribute and the resulting class has an InitializeComponent method, containing the C# code that creates all the controls specified in the XAML.
Note: I refer to code-behind because of my own familiarity with legacy .NET UI frameworks. Furthermore, the blasphemy continues by ignoring the popular UI architectural practices, such as MVVM. My goal is simplicity and raw functionality, rather than to impress with my pattern prowess (or lack thereof). For those who would be offended, I beg forgiveness in advance.
The code-behind above has a constructor that calls InitializeComponent. The crux of this factoid is that you now know that all controls on the page will be instantiated and initialized after the InitializeComponent method call, making them safe to call. In contrast, those controls don’t exist before the InitializeComponent call. Right-now the XAML and associated code-behind are nearly empty, except for a Grid, the next section discusses what type of data will be shown in the UI.
Tip: Drilling down on MainPage.xaml.cs in the project in Solution Explorer will allow you to see the generated code (build the project first) in a VS generated file named MainPage.g.i.cs.
Building the ViewModel
The ViewModel is a class I’m building to define what information will display in the XAML. The XAML is the View and the data bound to the View is a ViewModel. (Somewhere in this stream, the pattern-police are bound to bust me.) The TweetViewModel in this application is shown below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LinqToTwitterPublicQuery
{
public class TweetViewModel
{
public string Name { get; set; }
public string Tweet { get; set; }
public string ImageUrl { get; set; }
}
}
The properties in the code above will hold data for an individual user’s name, tweet text, and URL where their profile image is stored. Now, lets look at the XAML to see how this data is displayed.
Designing the UI
The look and feel of the UI is defined with XAML, which leads back to MainPage.xaml. We’ll enhance the existing Grid with a Button to load tweets and a ListBox to display the tweets. Here’s the updated MainPage.xaml:
<UserControl x:Class="LinqToTwitterPublicQuery.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:DesignHeight="768" d:DesignWidth="1366">
<Grid x:Name="LayoutRoot" Background="#FF0C0C0C">
<Button Content="Refresh Public Tweets" Height="72" Width="365"
HorizontalAlignment="Left" Margin="500,66,0,0"
Name="RefreshButton" VerticalAlignment="Top" />
<ListBox Height="465" HorizontalAlignment="Left" Margin="5,144,0,0"
Name="PublicTweetListBox" VerticalAlignment="Top" Width="1355">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" Height="132">
<Image Source="{Binding ImageUrl}"
Height="73" Width="73"
VerticalAlignment="Top" Margin="0,10,8,0"/>
<StackPanel Width="370">
<TextBlock Text="{Binding Name}"
Foreground="#FFC8AB14" FontSize="28" />
<TextBlock Text="{Binding Tweet}"
TextWrapping="Wrap" FontSize="24" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</UserControl>
Within the Grid in the XAML above, there’s a Button and a ListBox. As indicated by its name, Button is for refreshing the list of public tweets, which I’ll describe the inner workings for soon. ListBox normally displays a list of strings as it’s default behavior, but this application needs special formatting for the ImageUrl, Name, and Tweet properties of the bound TweetViewModel instances. This is where data templates come in.
As you can see above the DataTemplate element resides within the ListBox.ItemTemplate property element. The purpose of this DataTemplate is to define the shape of the data to display. The bindings of the data are specified between curly braces, with ImageUrl bound to the Source property of an Image control, Name bound to the Text property of the first TextBlock, and similarly Tweet is bound to the Text property of the second TextBlock.
Tip: When I show you the final image of the application running, you can refer back to this XAML so you can see how each control is positioned.
I’ve explained how the properties of each TweetViewModel instance is bound to the UI, but still need to show you how to bind the entire collection so the ListBox can find it’s data, which is next.
Binding a Collection of Tweets to the UI
To operate this application, the user will click on the RefreshButton, from the MainPage.xaml in the previous section. The Button Click event handler is where the magic happens, where the program uses LINQ to Twitter to get public tweets and binds those tweets to the ListBox. To get started on this part, double-click the Button in the UI (Yes, I know I said everything in the UI would be done by typing XAML, but this is so fun and easy). VS will add a handler to the code-behind and take you there. Here’s the code-behind, populated with code that does the binding:
Note: Be sure to add a project reference to the LinqToTwitter.dll assembly you downloaded earlier.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using LinqToTwitter;
using Windows.Foundation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;
namespace LinqToTwitterPublicQuery
{
partial class MainPage
{
public MainPage()
{
InitializeComponent();
}
private void RefreshButton_Click(object sender, RoutedEventArgs e)
{
var twitterCtx = new TwitterContext();
var tweetVM =
(from tweet in twitterCtx.Status
where tweet.Type == StatusType.Public
select new TweetViewModel
{
Name = tweet.User.Name,
Tweet = tweet.Text,
ImageUrl = tweet.User.ProfileImageUrl
})
.ToList();
PublicTweetListBox.ItemsSource = tweetVM;
}
}
}
The RefreshButton_Click method above is the handler for the Click event of the button, which you can now see if you look at the XAML in your IDE after double-clicking the button. The code above does a normal LINQ to Twitter query for tweets from the public timeline and projects into a List of TweetViewModel.
What’s important to the binding story is that the code assigns the resulting collection to the ItemsSource property of PublicTweetListbox. When the ListBox renders, it iterates through this list, binding each property of each TweetViewModel in the list according to the binding directives specified in the XAML earlier.
To run the application, press F5 and you’ll see a screen with a button but no tweets. Push the button and you’ll see tweets show up in a scrollable list, similar to the image below: 
Summary
You learned how to set up an application with VS11 and the different artifacts that are created for you. I showed you a few things about MainPage.xaml and it’s associated code-behind. Then you saw how to create a ViewModel, specify how to display data from the ViewModel, and how to bind Twitter data to the View. Now you have a working Windows 8 Metro application that displays tweets, via the LINQ to Twitter library.
@JoeMayo