News

My Stats

  • Posts - 49
  • Comments - 33
  • Trackbacks - 0

Twitter












Tag Cloud


Recent Comments


Recent Posts


Archives


Post Categories


Image Galleries


 

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:

MVVM

 

 

 

 

 

 

 

 

 

 

 

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:

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


 

Released LINQ to Twitter v2.0.23: http://bit.ly/AoKglP

@JoeMayo


 

Installing Windows 8 Developer Preview isn’t always simple.  It was troublesome on a 32-bit machine, but much easier on x64. 

Since Win8’s debut at Build last September, VirtualBox supports installing Win8 natively, so you’ll want to download the latest version of VirtualBox to make sure you don’t have problems. 

Another good option is VMWare.  They have a free product, VMWare Player, that runs well.  The only problem is it doesn’t have native Win8 support, but don’t let that get in the way.  This blog post, [Guide]Install Windows 8 on VMware Workstation with VMware Tools, has been helpful for me.  Here’s the real trick to getting this to work, as explained in the blog post: instead of loading the OS right away, check the option that say’s you’ll load it manually later.  Then, in the hardware configuration for New CD, specify the location of the *.iso file.

Of the two VMs, I prefer VMWare because of it’s display, performance, and ease of use.  VirtualBox is easier to install because of the native Win8 support, but it seems cumbersome with display resolution messages popping up and window sizing.  In contrast, once you get past the VMWare Player install glitch, everything just works perfectly.

@JoeMayo


 

If you're a Pearson author, you might be interested in signing this: An Open Letter to Pearson about SOPA/PIPA:http://martinfowler.com/articles/pearson-sopa.html

@JoeMayo


 

Here’s a site, by Lucian Wischik, that contains 101 Async Samples:

http://www.wischik.com/lu/AsyncSilverlight/AsyncSamples.html

There are examples in both C# and VB.  Some examples have a selector that lets you toggle between .NET 4.0 and the new Async syntax.  Each example has a run button so you can execute and see the return value. Throughout, you’ll see many different ways to use Async.  I think it’s a very nice resource.

@JoeMayo


 

While adding a new feature to the LINQ to Twitter Search API, I made significant changes to the Search entity that will break existing code. The new feature is support for Tweet Entities, a recent addition to Twitter’s Search API.  I’ll cover Tweet Entities support after explaining what has changed.

Motivation for Change

When Twitter implemented Tweet Entities for their Search API, they only supported JSON format.  LINQ to Twitter used ATOM for Search API queries; so, I didn’t have a choice on data formats.  What I found during analysis was that the fields of the JSON format differed significantly from the ATOM format.  More specifically, the the ATOM format contains more metadata than what’s necessary in JSON.  Since I had to make the switch anyway, I decided to refactor the naming so it matched the JSON format more closely – the benefit being that if you had to look at the Twitter API docs, the match between LINQ to Twitter Search entity property names and the Twitter API docs would be closer.  That said, in most cases, the property names are very similar or haven’t changed at all.  Overall, the changes, described below, will make the API more approachable and discoverable.

List of Changes

  • Search no longer derives from AtomFeed. Instead, all return properties are members of Search. (AtomFeed, AtomEntry, and AtomAuthor types still reside in the library, but they aren’t associated with Search anymore.)
  • Returned tweets now reside in the Results property of the Search entity (previously Entries property of AtomFeed), which is a list of SearchEntry.
  • SearchEntry has a normal ID, so you no longer need to parse it out like you did with the ID property of AtomEntry.
  • The ResultType property is now in a MetaData property, along with number of recent retweets.
  • SearchEntry has a CreatedAt property that is a DateTimeOffset of the time returned from Twitter as opposed to being translated in your local time.
  • Most existing properties correspond to existing AtomFeed properties, but many names have changed. (i.e. instead of using the Content property, you would now use the Text property)
  • Properties no longer supported (don’t appear in the JSON format) include: Alternate, Self, Title, Updated, Language (output), and TwitterWarning.
  • The RawResult property of TwitterContext will now contain a JSON formatted response (no longer an ATOM formatted response).

The impact of this change only affects how your application processes returned results from Twitter searches. All input parameters are still the same.  These changes facilitate support for Tweet Entities, described next.

The Tweet Entities Enhancement

Tweet Entities are metadata and other bits of information that Twitter extracts from a tweet, saving you the time of parsing the information yourself.  Current entities include hashtags, media, urls, and users.  Each entity has Start and End position properties in the tweet where it was extracted in addition to other entity-specific details.  The following codes shows how to find entities, showing counts of each entity type:

        public static void SearchIncludingEntities(TwitterContext twitterCtx)
        {
            var searchResults =
                (from search in twitterCtx.Search
                 where search.Type == SearchType.Search &&
                       search.Query == "@rschu" &&
                       search.IncludeEntities == true &&
                       search.PageSize == 100
                 select search)
                .SingleOrDefault();

            searchResults.Results.ForEach(entry =>
                {
                    Entities entities = entry.Entities;
                    Console.WriteLine(
                        "-- Entities --\n" +
                        "User: " + entities.UserMentions.Count + "\n" +
                        "Urls: " + entities.UrlMentions.Count + "\n" +
                        "Hash: " + entities.HashTagMentions.Count + "\n" +
                        "Media: " + entities.MediaMentions.Count + "\n");
                });
        }

The Query searches for results from someone I like to follow and whose tweets contain a variety of entity types.  Notice that I set IncludeEntities to true to ensure Twitter populates results with entities.  Here’s the description of the Search entity so you can see some of the structure and how to find entities:

- Search (this is searchResults above and contains relevant info for the Search instance)

-- … (other properties)

-- Results (List of SearchResult, containing info on tweets and metadata)

    --- Entities (Instance of Entities, containing the different entity types)

         ---- UserMentions (List of UserMention entities)

         ---- UrlMentions (List of UrlMention entities)

         ---- HashTagMentions (List of HashTagMention entities)

         ---- MediaMentions (List of MediaMention entities)

-- … (other properties)

As shown in the code snippet and hierarchy above, the Search.Results.Entities instance contains the entities you can read and use as necessary.

If you’ve previously worked with Status entities in LINQ to Twitter, you might notice similarities.  That’s because both the LINQ to Twitter Status and Search entities types are the same.

These changes haven’t been officially released, but you’re welcome to download the LINQ to Twitter source code.

Summary

You’ve seen how I refactored the Search results and how the LINQ to Twitter Search API now supports Tweet Entities. I hope you’ll see that the changes are for the better, trading a bit of discomfort for new functionality.

@JoeMayo


 

There’s an ongoing discussion in the community about various aspects of the Microsoft Most Valuable Professional (MVP) awards and this is a quick contribution I’ll make to share a few thoughts.  Recent events in this discussion include MVPs who either weren’t re-awarded and/or declined their award.  There are alignments and differences between their perspectives and mine, particularly in the areas of expectations and values.  This is one of my contributions to that on-going discussion.

In it’s simplest form, the MVP program is designed to recognize people who have contributed to the community.  Microsoft has provided their definition of an MVP, which I find to be a humbling experience.  Some people actively regard themselves as “experts” in their field and live the role through their behavior and words.  I’ve met people who describe themselves as “elite” and, regardless of what you think of a person who would make such a declaration, indeed they are often quite capable and their accomplishments are impressive.  Perhaps definition, expectation, and reality don’t always align, but no system is perfect and people will often fail to agree on the virtues of that system. My opinion of the MVP award system might not be unique, but there will be people who disagree.

I prefer to subscribe to a school of thought that recognizes the “award” part of the system.  Essentially, I did things that Microsoft decides as worthy of recognition.  Therefore, they’ve shown appreciation for my efforts by giving me MVP awards.  While humbled at the association with a group of respected professionals, I’m mostly grateful for the award and thankful for the recognition.  In the United States, we have a common saying, “Don’t look a gift horse in the mouth.”, which means that you shouldn’t be ungrateful when someone gives you a gift.  So, I don’t question Microsoft’s motivations, compare whether someone else is more or less deserving, or complain about the quality of the gift.  Sometimes it’s good to display grace and thankfulness.

@JoeMayo