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

Windows 8 Metro: Starting your first App from scratch

(3 votes)
Andrea Boschin
>
Andrea Boschin
Joined Nov 17, 2009
Articles:   91
Comments:   9
More Articles
2 comments   /   posted on Apr 18, 2012
Categories:   Windows 8 , General
Tweet

 
After the first article in this series, where I briefly discussed about design aspects of the new Metro interface, involving simplicity, flatness, emptiness and the pillars of this new beautiful paradigm, as promised, it is now time to start exploring the tools available to start create your applications.

At the date of this article, you have to be aware that I'm discussing about the "Windows 8 Consumer Preview" bits so, when then next releases will be available, something I've written might become obsolete due to changes made by the team. However, being at the second public preview of Windows 8 means that it is sufficiently stable to write something of reliable.

To follow this article and probably the next ones, it is obviously required an installation of Windows 8 CP. You can download it from this page. After you installed the operating system, you have to install Visual Studio 11 Express beta and Blend. These tools are included in the SDK you can download from the same page. My suggestion is to use a Virtual Machine to host all this software because when it will be obsoleted by a new version you can easily delete the virtual machine and create another one from scratch. Finally, it is important to download the "design assets", a 48MB zip files that contains a number of templates and images to help designers and developer to work with Metro constraints. I will be back to some of these templates in following articles.

Meet the Visual Studio IDE

imageGive that you downloaded and installed all the requirements, I guess you have firstly opened Visual Studio 2011 and problably you have been doomed by the great difference between its IDE and the previous versions. Since Visual Studio 2010 has been a big step with its new user interface, the IDE you have just opened makes a triple jump forward and embraces a number of Metro UI pillars, first of all the one I posed at the first in my list, that says "Be Authentically Digital". The new Visual Studio IDE have lost any minimal skeuomorphism in favor of a more flat appearance.

At the moment I've suspended my judgement about this new look&feel. The reason for this suspension is that I'm too much accustomed to the older interface and I'm now too much confused to be objective in my judgment but I need to be in touch with it for sometime to understand if this interpretation of Metro pillars makes me happy. What I can say at the moment is that I do not have any nostalgia of the skeuomorphic UI of VS2010 but I think they should have to use a more wide palette to avoid to make interface flatness to be semantically flat.

From the functional point of view, the IDE has a number of advantages. As an example I've added a screenshoot of the new Solution Explorer. What immediately catches the eye is the new hierarchy that is able to show the structure of the classes, methods, properties and so on. Another new feature is the automatic preview of files. When you select a file in the explorer, it is automatically opened as an interactive preview and if you make a change in the code, the file is finally opened. Hard to explain but simple to try if you select *.cs files in the tree.

Create and understand the project structure

imageOnce you gained the "New Project" window from the start screen or from the File menu, you choose between a number of templates. Metro applications can be created using two ways. If you like you can embrace HTML5 and Javascript or you can choose to use XAML coupled with C#, VB.NET or C++. The choose of the language to use currently is not matter of features because there are very few differences between what you can do in HTML or XAML. It is for sure matter of skills and development effort. Coupling XAML with C# is the most effective and fast way to develop a Metro application and it should be the primary choice when you are doing something more than an exercise. C# let you have real object orientation, compile time checking and other facilities. If you or your team have strong HTML skills, nothing prevent you from use it and Javascript but you have to plan for almost double or triple of the development time. It is for this reason in this series I will cover primary XAML and C#.

The templates in Visual Studio are modeled on this choice; you have templates for HTML+Javascript, XAML+C#, XAML+VB and XAML+C++. As the figure shows you have three templatates available:

  • Blank: is the most simple template and probably it will be always the better point to start from.
  • Grid: It creates an application the uses the new GridView control as the main Application Hub.
  • Split: It is an example of an application that splits contents in columns.

If Grid and Split templates are good for the first exercises, the Blank Application template is probably to most useful for real world purposes. After you create the project you will get the structure shown in the Solution Explorer screenshot in the previous paragraph. There is a number of items in the project, mostly of them are known to people that have already used Silverlight but other are specific to Metro applications. Here is the most important elements:

  • App.xaml/App.xaml.cs - Silverlight, Windows Phone and WPF developers already known this file. It handles the lifetime of the application. In Metro apps it handles events like Launched, Suspending, Activated and Resume. These can be used to manage the state of the application when it is suspended by the operating system. In the OnLaunched method, called when the application starts, it is initialized the main Frame. Metro applications are basically navigable applications; nothing prevents to inject directly a page instead of a Frame but you lose the entire navigation facilities.
  • BlankPage.xaml - This is the first page your application will show. If you want you can change it by editing the App.xaml.cs file and it does not have nothing different from every other page. Every page takes a reference to the main frame and can use it to navigate from one to another.
  • Application1_TemporaryKey.pfx - This file is a self generated certificate, required to sign the application package. To run in the metro AppContainer, an application needs to be signed so Visual Studio automatically generates a certificate and adds it to the project. The certificate is used for development purposes. It happened sometimes I've got errors caused by a not trusted certificate. In the case, you can manually regenerate the certificate or try to add it to the Windows Trust Root store of the machine where you work.
  • Package.appxmanifest - This represents the manifest of the application. The manifest contains all the informations required to run the application, define its capabilities, the way it communicate with other apps and how it is packaged. If you double click the file you get an editor that let you easily change its content. There is a number of things you can define: application logos, orientation, titles and notifications. You can also determine capabilities that is what the application can and can't do. Finally if you needs to manage the certificate this is the right place, going to the packaging tab.
  • Common (directory) - The content of this directory is someway strange. Inside it there are a number of classes that helps to manage layout, databinding and a bunch of converters. It contains also a ResourceDictionary (StandardStyles.xaml) with a series of styles. I think it is strange because I expect to have mosto of them compiled inside an assembly but have a look at this directory because i may contains something you really need.

imageThe first time you compile or run an application, Visual Studio (but also Blend) asks you to create a developer account. To accomplish this task you have to enter a live id account and you will be granted of a 1 month long license that you can use for free. Every time you activate another instance of Visual Studio (e.g. creating another virtual machine) your license is renewed and the month starts again.

Create your first app

Now that the project has been created you can start to implement your application interface and logic. For the first touch I will avoid a simple Hallo World but I'll drive you to create a single page application that is able to download a rss feed and display the titles in a grid layout. Inside this very basic app (view a screenshot on the right side) I used some of the interesting features of XAML for Metro.

All the code of the application is inside the BlankPage.xaml and BlankPage.xaml.cs files. As usual the xaml file represents the user interface description and the cs file is the codebehind of the page. Here is the very basic XAML content of my application. You have simply to cut & paste it in the BankPage.xaml file (be aware I called it Application1):

   1: <Page
   2:     x:Class="Application1.BlankPage"
   3:     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   4:     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   5:     xmlns:local="using:Application1"
   6:     xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
   7:     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
   8:     mc:Ignorable="d">
   9:  
  10:     <Grid Background="White">
  11:         <ItemsControl x:Name="items" VerticalAlignment="Center" HorizontalAlignment="Stretch">
  12:             <ItemsControl.ItemContainerTransitions>
  13:                 <TransitionCollection>
  14:                     <EntranceThemeTransition />
  15:                 </TransitionCollection>
  16:             </ItemsControl.ItemContainerTransitions>
  17:             <ItemsControl.ItemsPanel>
  18:                 <ItemsPanelTemplate>
  19:                     <VariableSizedWrapGrid Orientation="Horizontal" MaximumRowsOrColumns="3" 
  20:                                            ItemWidth="240" ItemHeight="120" HorizontalAlignment="Center" VerticalAlignment="Center" />
  21:                 </ItemsPanelTemplate>
  22:             </ItemsControl.ItemsPanel>
  23:             <ItemsControl.ItemTemplate>
  24:                 <DataTemplate>
  25:                     <Border Padding="10" Margin="10" d:DesignWidth="387.5" d:DesignHeight="101.5" 
  26:                             PointerReleased="HandlePointerReleased"
  27:                             BorderBrush="#FF666666" BorderThickness="1" 
  28:                             Background="#FFFF9900" Tag="{Binding}">
  29:                         <TextBlock Text="{Binding Title.Text}" TextWrapping="Wrap" Foreground="White" FontSize="16" />
  30:                     </Border>
  31:                 </DataTemplate>
  32:             </ItemsControl.ItemTemplate>
  33:         </ItemsControl>
  34:     </Grid>
  35: </Page>

The main content of the screen is a simple ItemsControl. This control let you display a collection and apply a DataTemplate to define the elements used to visually represent each item in the collection. The ItemsControl usually have a stacked layout; to display elements in a grid I use a layout element called "VariableSizedWrapGrid". This element organizes the items in a grid using a layout similar to the Silverlight's WrapPanel.

In the ItemTemplate property I've created a DataTemplate with a simple Border and TextBlock. This will display the title of an item into a rectangle. Finally, to make the application a bit more pleasant, I've added a EntranceThemeTransition that gives a beautiful entrance effect hard to describe using words. Then go to the BlankPage.xaml.cs file and change the OnNavigatedTo method and enter the following code:

   1: protected async override void OnNavigatedTo(NavigationEventArgs e)
   2: {
   3:     this.items.ItemsSource = await GetFeed();
   4: }
   5:  
   6: private async Task<IEnumerable<SyndicationItem>> GetFeed()
   7: {
   8:     try
   9:     {
  10:         Uri uri = new Uri("http://www.xamlplayground.org/syndication.axd");
  11:  
  12:         SyndicationClient client = new SyndicationClient();
  13:  
  14:         var feed = await client.RetrieveFeedAsync(uri);
  15:  
  16:         return feed.Items;
  17:     }
  18:     catch(Exception ex)
  19:     {
  20:         Windows.UI.Popups.MessageDialog dlg = new Windows.UI.Popups.MessageDialog(ex.Message);
  21:         dlg.ShowAsync();
  22:         throw ex;
  23:     }
  24: }
  25:  
  26: private void HandlePointerReleased(object sender, PointerEventArgs e)
  27: {
  28:     FrameworkElement border = sender as FrameworkElement;
  29:  
  30:     if (border != null)
  31:     {
  32:         SyndicationItem item = border.Tag as SyndicationItem;
  33:         Windows.System.Launcher.LaunchUriAsync(new Uri(item.Id));
  34:     }
  35: }

The code here downloads the feed of my weblog at http://xamlplayground.org and then load it into the ItemsControl using the ItemsSource property. Pay attention to this code that use the awesome async and wait keywords. I will be back on asynchronous programming later in this series, but to full understand this code think at these keywords like your best friends to simplify the calling of asynchronous methods thanks to the integration of the Task Parallel Library. Take note also the that asynchronicity hightly pervades Metro applications and WinRT at a level you don't expect for sure.

imageAfter you completed the code in XAML and C# as I described you can run the application using F5 in Visual Studio. This task deployes the application to the AppContainer and runs it in debug mode like every other application you are habit to develop. Using the Metro UI of your operating system is probably good to appreciate the user interface aspects, but if you do not have a touch enabled monitor you can use the simulator. It allows to use the mouse like a finger on your touch device and includes the simulation of gestures like drag, hold, pinch and rotate but also a gps tool to inject locations in tested applications. It is not like having a true touch enabled device but you can spare a lot of money and start today your development.

Deploy and run

imageBut, what it happens when the application is compiled and then deployed? Visual Studio is a good friend for the developer but it hides the details that are automatically accomplished when you hit F5. This is good for most of the times but annoying if you are curious to know the insides of Metro apps. I will start saying that your C# code is simply an abstraction created on top of WinRT, the core runtime that is shared between all the consumer languages (C#, Javascript, VB.NET and Managed C++). This abstraction is made to (luckily) hide the fact that under the hoods of WinRT there is still C++ and COM. These APIs are exposed to your C# code with a bunch of metadata files that "translates" them to the C# compiler like normal assembly references. These metadata containers are known as .winmd files.

So, when you hit F5 in Visual Studio the very first operation is to compile your C# code connecting all the referenced APIs and, the product of this compilation is a exe file paired with a AppManifest.xml file and all the resources (mostly are xaml and images). All these files are created in the bin directory related to the target configuration. See  the image on the side for an example.

This is only the first stage. If you try to run the exe that is output of this stage you get an error stating that it can run only in the context of an AppContainer. This is because the compilation follows a new target output "appcontainerexe". So, after the compilation, the application needs to be packaged into a zip file (do you remember xap files?) called APPX before it is deployed. To create this package Visual Studio uses the MakeAppx.exe utility. You can manually pack or unpack appx using this executable from a command prompt targeting Visual Studio 2011.

The last step before the package is deployed is the signing process. For this purpose Visual Studio takes the certificate linked to the project and using the signtool.exe utility it signs the package then deployes it to the Metro AppContainer. To fully satisfy your curiosity you can manually accomplish this task using the Add-AppxPackage cmdlet included in powershell. Here is a reference to all the cmdlets available for common tasks: http://technet.microsoft.com/en-us/library/hh856045.aspx. For example running the Get-AppxPackage without parameters you will get the full listing of installed apps.

Moving forward to the next step

In this article I've introduced a numeber of features, some have been explained and other remains open for the next articles in this series. Now that that you have been introduced to the concepts of Metro an you wrote your first example it is time to take in serious consideration the programming aspects of a Metro application. In the next article I will introduce how to handle the layout and navigation. Layout is a very important aspect in Metro since it involves the orientation and the view states. Navigation let you expand your scope to multipage apps. For the moment enjoy yourself with attached code.


Subscribe

Comments

  • DonBurnett

    Re: Windows 8 Metro: Starting your first App from scratch


    posted by DonBurnett on Apr 19, 2012 06:09
    This is a great start.. Thanks for bringing this forward.  I have had some serious reservations about teaching people Windows 8 applications without a design first philosophy. The only think I am really disappointed so far is in the sample's UI, it's not the tenants of a good metro app design so far and I am a bit discouraged (because I know the author and he is brilliant (yes you are!) and beginning app looks like the Hollywood squares or tic-tac-toe.. I would have loved to see a discussion about implementing appropriate interaction in a METRO app.

    What you .NET developer guys aren't getting is this is a design first environment.. Anytime you don't design how the UI works and the user accesses it's functionality this it's READY SET fail for the users..

    Could we talk in further continuations of this about how to add appropriate user interfaces for interactivity (where appbars are appropriate and not), and why you aren't building a phone for Windows App with all of that left over real estate.. 

    Could we also talk where "meta" interactivity should be used inside of content for manipulation and interactivity how to replace a menu with these kinds of controls and when it's appropriate to use a left or right top or bottom  AppBar or the control should go right inside the content afterwards.

    Could we also get some insight into the current metro controls in the beta such as the RichEdit Box and why it's methods and functionality do not allow for the same manipulation as the RichTextBox control I am typing into right now and how you can only insert an image, but formatting and manipulation won't be there without third party add-on controls.. 

    Also things like when to provide user with CONTEXT of where you are in an app as it's scrolls from side to side and being able to track where you have been.. These are all great questions that I look forward to in further installments.

    Thanks for getting the ball rolling with this it's a great first outting..
  • OBDSystems

    Re: Windows 8 Metro: Starting your first App from scratch


    posted by OBDSystems on Apr 21, 2012 17:13
    Why did SilverlightShow Weekly Content Digist email direct me to this Windows 8 article???

Add Comment

Login to comment:
  *      *       

From this series