(X) Hide this
    • Login
    • Join
      • Generate New Image
        By clicking 'Register' you accept the terms of use .

Windows 8 and the future of XAML: Part 3: Using WinRT

(5 votes)
Gill Cleeren
>
Gill Cleeren
Joined Apr 02, 2010
Articles:   63
Comments:   6
More Articles
2 comments   /   posted on Feb 20, 2012
Tags:   windows-8 , xaml , winrt , gill-cleeren
Categories:   Windows 8 , General
Tweet

In this third part of our exploration of Windows 8 and WinRT, we’re going to start applying the concepts we learned about in the 2 first parts by using them in code. By now, you should have a good understanding of what Windows 8 Metro style applications are all about. In part 1, we’ve thoroughly explained how Windows 8 applications work inside the Metro environment. We’ve also looked at the improvements made to the desktop mode of Windows 8, which is a place where a lot of us will be spending most of their time I assume.

In Part 2, we’ve seen some very important concepts. We’ve covered WinRT itself: we’ve looked at its architecture and its cornerstones, such as the runtime broker, Windows Metadata and asynchronous development. We’ve also touched on the Windows 8 tailored profile.

This brings us to Part 3. In this article, we’ll start writing code that makes use of WinRT components. Although most of us like to write XAML and C# code, we’ll leave the regular path for once and we’ll write some JavaScript/HTML as well. After some “Hello Worlds”, we’ll dive in more advanced concepts including Capabilities, the Share contract, working with the webcam and some more. Here we go!

Hello World… This time for real

In part 2, I already had the same heading. However, we hadn’t really written any code yet. So let’s do that right now. Note that for all the code we are writing here, you need Visual Studio 11 Express for Windows Developer Preview installed on a Windows 8 machine. To keep things simple, when I use the term”Visual Studio” from now on, it’s this version I’m referring to. If you have Visual Studio 11 installed on your Windows 8 environment as well, the templates that come with the Express edition will also be added to VS11.

A small disclaimer is in place here: the code written in this article is written and tested on the developer preview and may not work correctly with later releases.

Hello Visual Studio

When opening Visual Studio, you’ll notice that things haven’t changed a lot (of course, at the time of writing, we’re using a very early version). When clicking on the New Project link on the Start Page, you get the New Project dialog, shown below.

In part 2, we talked about the so-called language projections of WinRT. A language projection makes it possible to use WinRT, which is written in native code, from another language. Because of this, developers can keep using the language of their choice to write Metro style applications. The language projection makes sure that language constructs remain intact. Things like a constructor, the var keyword, the await keyword all remain the same if you choose to use WinRT from C#. The language projections that are available can be seen here: we can build Metro style apps from JavaScript, C#, VB and C++. All languages have the same project templates available as well.

Let’s start by selecting the C# option. Create a new project (just select the regular Application template for now) and name it HelloWinRTFromCs. Visual Studio opens a designer that should look familiar to the Silverlight developer. We have our regular drag-and drop interface and a XAML editor, as shown below.

In the XAML editor, we can start writing our typical “Hello World” application as follows:

<UserControlx:Class="HelloWinRTFromCs.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">
        <TextBlock Name="HelloWorldTextBlock" FontSize="42" Margin="20"></TextBlock>
        <Button Content="I'm the Hello World generator button" Name="HelloWorldButton"
            Click="HelloWorldButton_Click"></Button>
    </Grid>
</UserControl>

In the event handler of the Button, we write the following code:

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 HelloWinRTFromCs
{
    partial class MainPage
    {
        public MainPage()
        {
            InitializeComponent();
        }
 
        private void HelloWorldButton_Click(object sender, RoutedEventArgs e)
        {
            HelloWorldTextBlock.Text = "Hello World from SilverlightShow";
        }
    }
}

Ready? Start your debugging engines! Simply hit F5 as you’re used to. Your first Windows is now being prepared. If you take a look in the Output Window, you can see that an *.exe is being created and that *.exe is being packaged into an *.appxrecipe. This file is basically the deployment file that will be “hosted” inside of the Metro environment. After a few seconds, you’ll see your Metro app up and running as shown below. Hit the Button and you’ll be greeted with a nice Hello World from your app when you click the button.

Visual Studio also comes with a simulator. To use it to test your app on, simply select it from the debug options. The simulator is shown below.

Hello C++

Managed developers should feel reassured already a bit now that they’ve seen that it’s pretty much the same thing we’re doing to build a Metro style app. But what about C++ developers? Let’s build the same app but now from C++. The XAML code can be directly copied and pasted inside the new project. This will work since all XAML classes (such as Button and TextBlock) have now moved into the Windows.UI.Xaml namespace. This namespace is part of WinRT and it is thus the same one we’re using in both C# and C++.

The C++ code for the event handler is shown below.

void Application33::MainPage::HelloWorldButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
HelloWorldTextBlock->Text = "Hello World";
}

When running the application, you should get the exact same result. Behind the scenes, our C++ code is being compiled into a native x86 instruction stream (if we would be running this on an ARM-based device, this would be an ARM instruction stream). C++ is directly interacting with the WinRT components.

And why not… Hello JavaScript and HTML

To make the circle complete, let’s write a Hello World app from JavaScript as well. Of course, we’re unable to copy the XAML; JavaScript works in combination with HTML code. Create a new project and select JavaScript this time.

In the HTML code, write your Hello World app as follows:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>WinWebApp6</title>
    <!-- WinJS references -->
    <link rel="stylesheet" href="/winjs/css/ui-dark.css" />
    <script src="/winjs/js/base.js"></script>
   1:  
   2:     <script src="/winjs/js/wwaapp.js">
   1: </script>
   2:     <!-- WinWebApp6 references -->
   3:     <link rel="stylesheet" href="/css/default.css" />
   4:     <script src="/js/default.js">
</script>
</head>
<body>
    <b>Hello World</b>
</body>
</html>

More WinRT

Although new development platform or language you learn starts with Hello World, it doesn’t get you very far. Let’s look at some more concepts.

Selecting files on the local file system using the FileOpenPicker

Metro apps can’t directly access system resources such as the file system. It’s pretty much the same story as Silverlight that we have here: in-browser Silverlight apps can only get access to file if the user selects the file through an OpenFileDialog. In that case, Silverlight gets read-only access to the file. Apps with elevated permissions can get access to the local system.

In WinRT, we have file pickers. Such a picker allows the user to select a file on the “underlying” Windows desktop environment. In the following code, we are using the FileOpenPicker to allow the user to select an image, which we’ll then display in an Image control.

private async void SelectImageButton_Click(object sender, RoutedEventArgs e)
{
    var filePicker = new Windows.Storage.Pickers.FileOpenPicker();
    filePicker.FileTypeFilter.Add(".png");
    var selectedImageGuFile = await filePicker.PickSingleFileAsync();
 
    BitmapImage bitmapImage = new BitmapImage();
    bitmapImage.SetSource(await selectedImageGuFile.OpenAsync(Windows.Storage.FileAccessMode.Read));
    myImage.Source = bitmapImage;
}

Notice the line where we are selecting the file. It makes use of the await keyword. Every call that can take longer than 50ms is done asynchronously by default in WinRT. Silverlight developers are already used to writing async code: when accessing a service, this is the default. Traditionally, we solved this with a callback method. There’s nothing wrong with that. However, this new approach using the await keyword, makes things cleaner: all the lines that are behind the line with the await keyword are only executed when the asynchronous call is completed. Note that the method itself has the async keyword added to it.

When clicking the Button, the file picker displays itself as follows:

Again, through language projections, the asynchronous development is made natural in the language. In JavaScript, the same can be achieved through a JavaScript promise:

var picker = new Windows.Storage.Pickers.FileOpenPicker;
picker.fileTypeFilter.append(".jpg");
picker.pickSingleFileAsync().then;

Accessing the picture library and Capabilities

Next to the pickers API, Metro-style applications can also access some folders directly such as the pictures library. Although stating “directly” may not be very good, let me explain.

In Windows 8, Metro style applications can declare capabilities. A capability is a way for the application to declare that for it to function properly, it needs to have a certain permission. Such a permission can be accessing the webcam, sending text messages, accessing the picture, movie or documents library and quite a few more. This information will be used in the Windows Store: with this information, the Windows Store can notify the potential user that the application will have the declared permissions so that the user may decide on not installing the application. This is the same process as in the Windows Phone Marketplace.

Let’s take a look at working with capabilities. We’ll try them out using a project which can access the picture library. Create a new C# project and name it WorkingWithCapabilities.

To define a capability, we can open the appxmanifest file, included in each Metro style project. In the Capabilities tab, check the “Picture Library Access”.

In the XAML, add a GridView (we’ll look at the GridView later on, for now, just remember that it’s a control allowing you to scroll through items horizontally) as follows:

<GridView Name="PicturesGridView" Height="500" VerticalAlignment="Center"></GridView>

In the code-behind, add the following code:

public MainPage()
        {
            InitializeComponent();
 
            LoadImages();
            
        }
 
private async void LoadImages()
{
    StorageFolder picturesFolder = KnownFolders.PicturesLibrary;
 
    IReadOnlyList<IStorageFile> fileList = await picturesFolder.GetFilesAsync();
 
    foreach (IStorageFile file in fileList)
    {
        if (file.FileType.Equals(".JPG"))
        {
            var bmp = new BitmapImage();
            var f = await file.OpenAsync(FileAccessMode.Read);
            bmp.SetSource(f);
            Image image = new Image();
            image.Width = 200;
            image.Height = 200;
            image.Source = bmp;
            imageControls.Add(image);
            image.Tag = file;
        }
    }
    PicturesGridView.ItemsSource = imageControls;
}

Notice that we are accessing the Picture Library through the use of the KnownFolders enumeration, which gives us access to the folder from code. This code will however only work when you have indicated in the Capabilities tab that your app needs access to this folder. Then, we read out the files through another async call (remember, we are accessing the drive, which could be a slow process, hence, the async call). Finally, through data binding, we bind a list of images to the GridView. The running app is shown below:

Summary

In this article, we have done our first development in WinRT. We have looked at the first concepts as well, such as the file pickers and the capabilities. In the next article, we’ll continue on this path, exploring more concepts such as contracts/charms in Windows 8.

About the author

Gill Cleeren is Microsoft Regional Director (www.theregion.com), Silverlight MVP (former ASP.NET MVP) and Telerik MVP. He lives in Belgium where he works as .NET architect at Ordina (http://www.ordina.be/). Passionate about .NET, he’s always playing with the newest bits. In his role as Regional Director, Gill has given many sessions, webcasts and trainings on new as well as existing technologies, such as Silverlight, ASP.NET and WPF at conferences including TechEd Berlin 2010, TechDays Belgium – Switzerland - Sweden, DevDays NL, NDC Oslo Norway, SQL Server Saturday Switserland, Spring Conference UK, Silverlight Roadshow in Sweden, Telerik RoadShow UK… He’s also the author of many articles in various developer magazines and for SilverlightShow.net and he organizes the yearly Community Day event in Belgium. He also leads Visug (www.visug.be), the largest .NET user group in Belgium. Gill recently published his first book: “Silverlight 4 Data and Services Cookbook” (Packt Publishing). His second book, Silverlight 5 Data and Services Cookbook will be released March 2012. You can find his blog at www.snowball.be.

Twitter: @gillcleeren


Subscribe

Comments

  • SocalSam

    Re: Windows 8 and the future of XAML: Part 3: Using WinRT


    posted by SocalSam on Feb 28, 2012 22:28
    Nicely done!
  • atif

    Re: Windows 8 and the future of XAML: Part 3: Using WinRT


    posted by atif on Mar 14, 2012 20:57
    We expect some more articles and webinars of windows 8 consumer preview because from development preview to consumer preview there is alot changes are there so it would be great to have some webinars on consumer preview.

Add Comment

Login to comment:
  *      *       

From this series