Saturday, August 25, 2012

Using OData in Windows 8 Apps for Windows 8 RTM

The following is an excerpt from Chapter 6 of my book, Building Windows 8 Apps with C# and XAML.

The Open Data Procotol (OData) is a web protocol used for querying and updating data. It is a REST-based API built on top of Atom that uses JSON or XML for transporting information. Windows 8 applications have native support for OData clients once you download and install the client from:

http://go.microsoft.com/fwlink/?LinkId=253653

To access OData services, you simply add a service reference the same way you would for a SOAP-based web service. A popular OData service to use for demonstrations is the Netflix movie catalog. You can browse the service directly by typing http://odata.netflix.com/catalog/ into your browser. In most browsers you should see an XML document that contains various tags for collections you may browse. For example, the collection referred to as Titles indicates you can browse all titles using the URL, http://odata.netflix.com/catalog/Titles.

The Netflix project (available from Chapter 6 in the download available at http://windows8applications.codeplex.com) shows a simple demonstration of using this OData feed. The main URL was added as a service reference the same way the weather service was added in the previous example. The first step in using the service is to create a proxy to access it. This is done by taking the generated class from adding the service and passing in the service URL:

var netflix =
    new NetflixCatalog(
        new Uri(
            "http://odata.netflix.com/Catalog/",
            UriKind.Absolute));

Next, set up a collection for holding the results of an OData query. This is done using the special DataServiceCollection class:

private DataServiceCollection<Title> _collection;
...
_collection = new DataServiceCollection<Title>(netflix);
TitleGrid.ItemsSource = _collection;
Finally, specify a query to filter the data. This query is passed to the proxy and will load the results into the collection. In this example, the query will grab the first 100 titles that start with the letter "Y" in order of highest rated first:
var query = (from t in netflix.Titles
                where t.Name.StartsWith("Y")
                orderby t.Rating descending 
                select t).Take(100);            
_collection.LoadAsync(query);

Finally, as data comes in you have the option to page in additional sets of data. This is done by checking the collection for a continuation. If one exists, you can request that the service load the next set. This allows you to page in data rather than pull down an extremely large set all at once.

if (_collection.Continuation != null)
{
    _collection.LoadNextPartialSetAsync();                    
}

Run the included sample application. You should see the titles and images start to appear asynchronously in a grid that you can scroll through.

As in the previous example, the results of the web service are bound directly to the grid:

<Image Stretch="Uniform" Width="150" Height="150">
    <Image.Source>
        <BitmapImage UriSource="{Binding BoxArt.LargeUrl}"/>
    </Image.Source>
</Image>
<TextBlock Text="{Binding Name}" Grid.Row="1"/>

The Windows 8 development environment makes it easy and straightforward to connect to web services and pull data in from external sources. Many existing applications expose web services in the form of SOAP, REST, and OData feeds. The built-in support to access and process these feeds makes it possible to build Windows 8 applications that support your existing functionality when it is exposed via web services.

Jeremy Likness

Thursday, August 16, 2012

Quick Tip: Activating your Windows 8 Installation

Like many of you reading this, I was eager to jump online and download my copy of Windows 8 when it became available to developers yesterday. I pulled down the Windows 8 Enterprise SKU and installed it on my Samsung Series 7 Slate. The install went quickly - I was up and running in about 10 minutes - but I kept getting a nagging message to activate. It had never prompted me for the product key.

If I went through the Control Panel to activate it would generate an error message about volumes and folders, and through the Settings it would simply spin and come back and show not activated. I had to dig around a bit before I found this nice tip that I imagine will help you if you are having the same issue. Be sure you have your key.

From the Start Screen, type CMD to pull up the available command prompts.

Don't tap on the "Command Prompt" option. Instead, drag it slightly (or right-click if you are using a mouse) to select it, and choose the option "Run as administrator."

Now you can type a simple command on the command line:

slmgr.vbs -ipk "XXXXX-XXXXX-XXXXX-etc"

Replace the XXXXX nonsense with your full product key. That's it! This will set the product key for you. In my case, it activated immediately. If it doesn't, you have two options. One is to open the charm bar (mouse in lower right corner, thumb swipe from right, or Windows Key + C) and choose Settings, then "Change PC Settings."

There should be an option for Activation if you are not activated yet. The second is to navigate to your Control Panel, then System and Security, then System, and tap on the available link in the "Windows activation" area (mine shows I am already activated - and don't sweat the fact the screen cap shows that no pen or touch are enabled, because it was taken during a remote desktop session).

Enjoy your Windows 8! For more tips like this, grab your copy of Programming the Windows Runtime by Example.

Jeremy Likness

Thursday, August 9, 2012

Synchronous to Asynchronous Explained

I've posted several articles about the new async and await keywords that are available in Visual Studio 2012, but I still see some people struggle with the concept. How do you make a task asynchronous? When and where do you use the async keyword?

The answer is not simple because the need to process asynchronously depends on a variety of factors. There is overhead when you create a thread. It allocates memory and creates a new synchronization context. Having a thread communicate with other threads is even more expensive and adds complexity to your code. Fortunately, the teams at Microsoft introduced the Task Parallel Library to help simplify how you work with threads. I strongly recommend learning as much as you can about the Task object if you wish to master asynchronous programming.

There are many cases where the use of asynchronous code is straightforward, and my intent with this article is to show a very simple example to help illustrate how to create an asynchronous task and then use the new keywords to interact with it. The example is a very trivial program that computes prime numbers between 2 and 999999. You can follow along and build this in about 5 minutes.

First, create a new WPF application from Visual Studio 2012 that targets the .NET Framework 4.5. Add a simple listbox to MainWindow.xaml so the entire XAML looks like this:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <ListBox x:Name="PrimeNumbers"/>
    </Grid>
</Window>

Now add a new class and call it PrimeChecker. This is a static class that will check to see if a number is a prime number. The algorithm we'll use is a brute force algorithm that divides numbers until it finds a match:

public static class PrimeChecker
{
    public static bool IsPrime(int x)
    {
        if (x < 2) return false;
        if (x == 2) return true;
        for(var y = 2; y < x; y++)
        {
            if (x % y == 0)
            {
                return false;
            }
        }
        return true;
    }
}

In the code-behind for the MainWindow, declare an observable collection to hold the prime numbers:

private ObservableCollection<int> _primeNumbers =
    new ObservableCollection<int>();

Hook into the Loaded event for the page:

public MainWindow()
{
    InitializeComponent();
    Loaded += MainWindow_Loaded;            
}

Once the page is loaded, you will assign the observable collection to the source for the list box control, then iterate through numbers and call the checker to only add those numbers that are prime:

void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
    PrimeNumbers.ItemsSource = _primeNumbers;
    for(var x = 1; x < 999999; x++)
    {
        if (PrimeChecker.IsPrime(x))
        {
            _primeNumbers.Add(x);
        }
    }
}

You can now compile and run the program. If you set a breakpoint in the loop, you will see that prime numbers are being computed and added to the collection. However, the application itself will freeze and you won't see anything. This is because all of the computations are happening on the same thread, which happens to be the main UI thread. This will freeze that thread and prevent the system from updating the display and accepting user input. This is obviously not the desired effect. What would make more sense is to do the heavy lifting, or the brute force algorithm to determine if a number is prime, on a separate thread that does not block the UI. This is easily done in a few steps. First, add a new method to the PrimeChecker class. Note I'm following the standard convention of marking an asynchronous method with the Async suffix:

public static Task<bool> IsPrimeAsync(int x)
{
    return Task.Run(() => IsPrime(x));
}

That's it. That's the only code needed to take the computation and run it on a separate thread. The Task takes care of it. Notice that the return is typed to the actual value we want to inspect (boolean) but wrapped in a Task object. Now that you have the work being performed asynchronously, how do you interact with the result? This takes two simple steps.

First, declare your intent to wait for an asynchronous task by prefixing the method with the async keyword. We are still going to use the MainWindow_Loaded method, so it will now look like this:

async void MainWindow_Loaded(object sender, RoutedEventArgs e)

Next, change the call to check for a prime number to use the asynchronous method, and then simply wait for it. The await keyword specifies that the task should run and return a result, but the thread should not block while waiting. It is as simple as changing the line to this:

if (await PrimeChecker.IsPrimeAsync(x))

And that's the beautify of the new keywords. Without those keywords, you would need to explicitly wait for the thread, either by using a helper method on the Task or by using events and registering for a completion. This would fragment your code and if you had a lot of asynchronous tasks could render it very difficult to read and maintain. The new keywords make it easy to both create asynchronous methods and consume them inline without blocking. The entire method now looks like this:

async void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
    PrimeNumbers.ItemsSource = _primeNumbers;
    for(var x = 1; x < 999999; x++)
    {
        if (await PrimeChecker.IsPrimeAsync(x))
        {
            _primeNumbers.Add(x);
        }
    }
}
When you run the application this time, you'll see the list quickly start to fill with the list of prime numbers. You can scroll the list while it is computing because the main thread is no longer frozen by the brute force computations.

Jeremy Likness

Wednesday, August 8, 2012

Hello Nokia Lumia 900 - and thanks, Endomondo

After years of using a Samsung Focus (older generation) for Windows Phone 7, I recently received my brand new neon blue Nokia Lumia 900. A trip to the AT&T store had my SIM quickly moved from the regular SIM card for the Samsung to the micro SIM that the Nokia uses. I was up and running in minutes. After that, the fun began.

First, the Windows Phone 7.5 OS itself is phenomenal. It literally took me seconds to set up my various emails. The best part was the seamless integration with Office 365. I entered my email and password, it figured out that I was using Office 365 and connected my Exchange, linked me to the SharePoint site, and sent me to download the Lync application so I can communicate with my coworkers on the phone. All of that was literally without a hitch. I plugged into the laptop and a few minutes later had all of my music and video collection downloaded.

I've been so used to 3G that I about choked the first time I started using the web and downloading apps over the LTE and 4G connections. They really are fast. Even better though is the built-in Internet Explorer. I didn't realize how much I was missing on the 7.0 version compared to 7.5 - it renders sites well and unlike the older browser most sites detect the mobile mode. When in desktop mode the pages load quickly and I was surprised at how much I could really do from the phone browser.

I haven't had a front-facing camera on my smart phone before, so I had to check out the video chat. Tango comes installed on the phone. I asked my daughter to load the same app on her iPhone. A few minutes later, we were video chatting - it just worked. The display is beautiful, the built-in camera at 8 megapixels does a great job, but I was also surprised to listen to the sound. Sometimes I like to sit on the deck and just play music through my phone. The Samsung wasn't very audible, whereas the Lumia has loud speakers that are very easy to hear.

The best part about switching though, and what led me to write this blog post, was my running software. I've been using RunKeeper for some time and was surprised to find it had been yanked from the Windows Phone market when I tried to install it on the new phone. That meant going to a new application. I downloaded MapMyRun and tried it, and I'm not sure if it was flakey GPS or failure to run under the lock screen by default, but my 4.5 mile jog was logged in at 31 miles. Apparently I was running a 1:30 minute mile. I then decided to download Endomondo Sports Tracker. Wow! I'm glad I did ... in fact so much I decided to write this post/review when I normally don't do these.

Pretty much everything about the application addresses what I want when I'm going on a run. First, it is integrated with music from within the application - I can start my play list right there and not have to launch it separately. Next, you have the option to count down before it starts tracking an activity. This is important to me because I usually kick it off and then shove the phone into the sleeve of the arm band I have. The countdown gives me time to get that done and be ready to start. The application simply speaks when the countdown is done. Finally, as you are running, you can configure it to give you updates during the run. It is awesome when the phone is not accessible due to the arm band to hear when I cross a mile mark, hear my total time, my lap time, and my estimated total time for the run. All in all it's a solid product and I had a really enjoyable run using it.

There you have it - an awesome new phone and application that I was so happy with I decided to write this post.

Jeremy Likness