Geeks With Blogs

News
Joe Mayo Devices and Things

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:

NewProject

 

 

 

 

 

 

 

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:

CreatedProject

 

 

 

 

 

 

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: RunningApp

 

 

 

 

 

 

 

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

Posted on Thursday, January 26, 2012 10:11 AM Twitter , LINQ to Twitter , Windows 8 | Back to top


Comments on this post: Using LINQ to Twitter in Windows 8 Metro Apps

# re: Using LINQ to Twitter in Windows 8 Metro Apps
Requesting Gravatar...
I tried using the Library in a dummy Metro app , but got the error :
"The project targets '.NETCore' while the file reference targets '.NETFramework'. This is not a supported scenario"

Did I missed something ? Is there a different version of LinQtoTwitter built for metro style ?
Left by swapnil on Apr 02, 2012 12:37 AM

# re: Using LINQ to Twitter in Windows 8 Metro Apps
Requesting Gravatar...
This code was written for the Developer Preview. I'm working on a version of LINQ to Twitter that runs as a Portable Library.
Left by Joe Mayo on Apr 02, 2012 7:23 AM

# re: Using LINQ to Twitter in Windows 8 Metro Apps
Requesting Gravatar...
When adding the reference to the .dll I get an error ("the project targets .NETCore when the file reference targets .NETFramework. This is not a supported scenario.")
Left by Jason Cartwright on Apr 09, 2012 10:43 PM

# re: Using LINQ to Twitter in Windows 8 Metro Apps
Requesting Gravatar...
Jason,

This example was written on the developer preview. The consumer preview requires a compatible library. I'm currently working on creating a version of LINQ to Twitter that runs as a Portable Class Library.
Left by Joe Mayo on Apr 10, 2012 7:58 AM

Your comment:
 (will show your gravatar)


Copyright © Joe Mayo | Powered by: GeeksWithBlogs.net | Join free