Introduction to Windows 8 Development
With Windows 8, Microsoft introduced significant changes to the underlying platform and user interface. These new features include a new start screen experience, Windows stores to purchase apps from a single repository, and a new platform known as Windows Runtime (WinRT).
WinRT provides a new set of APIs and tools to create a new style of touch-first apps that are fast and fluid. These apps are generally called Windows Store Apps.
For the purposes of this book, some of the key things to know about WinRT and Windows Store apps include
As this book is more about data access in Windows 8, this chapter provides an overview of the Windows 8 app framework and briefly looks into the development choices, UI data controls, MVVM patterns, and other necessary concepts that will be used in various examples throughout this book. In the later part of this chapter we’ll write our first data-driven Windows 8 App that displays the New York Times Best Sellers list.
In Figure 1-1, we see the Windows 8 modern-style app framework compared to that of desktop applications, where both share the same Windows core OS services. If we look at the desktop application section, JavaScript and HTML are used to target Internet Explorer, C and C++ are used for Win32 apps, and C# and Visual Basic for .NET and Silverlight. Each of these will have a separate set of APIs. But with Windows 8 Apps, we have one set of APIs that for WinRT whether we use XAML, C#, C/C++, Visual Basic, HTML/CSS, or JavaScript.
Figure 1-1. Windows App framework
For developing Windows 8 Apps, we can choose either of the two development paths shown in Figure 1-2.
Figure 1-2. Development choices
In the HTML path we will be able to use the traditional Web technologies like HTML5, CSS, and JavaScript. For presentation, you use HTML tags such as div, table, spans, and input, and CSS for styling. For coding, JavaScript can be used. Apart from the HTML controls, Windows Library for JavaScript provides a set of new controls designed for Windows Store Apps. This WinJS library is our path for the WinRT.
If you are a WPF, Silverlight, or Windows Phone developer, then designing the UI and presentation layer using XAML is an ideal fit. Here we will be using C#, Visual Basic, or C++ for coding.
Creating the New York Times Best Sellers App
The New York Times Best Sellers app is a simple Windows 8 App that uses the MVVM pattern to display the New York Times Best Sellers list. Building this app is a starting point to learn to use Visual Studio 2012, the MVVM framework, data binding, data controls, and other necessary concepts to create a data-driven Windows 8 Modern UI app.
Introducing the MVVM Application Framework
Model-View-ViewModel (MVVM) is the most widely used framework in WPF/Silverlight/Windows Phone XAML-based development. Considering MVVM as the central concept of Windows 8, it supports XAML-based development and is ideologically similar to the technologies that use MVVM as the application framework, so it is an ideal choice. This chapter introduces you to the MVVM framework. In later chapters you will learn about some of the most commonly used MVVM frameworks like MVVM Light and Prism.
The MVVM pattern splits the user interface code into three conceptual parts: Model, View, and ViewModel (see Figure 1-3). The concept of the ViewModel is the new, and it controls the View’s interactions with the rest of the app.
Figure 1-3. The basic relationships of the MVVM framework
These are the some of the advantages of using MVVM over other patterns:
Setting Up the Development Environment
Download the developer tools from http://dev.windows.com. The developer tool includes the Windows 8 Software Development Kit, a blend of Visual Studio and project templates. Microsoft Visual Studio for Windows 8 is our integrated development environment (IDE) to build Windows 8 Apps and this version runs only on Windows 8.
Optionally, Microsoft Visual Studio 2012 can also be used. The full version has advanced debugging tool support, multi-unit testing framework and refactoring support, code analysis, profiling, and support for connecting to Team Foundation Server.
Note Windows 8 Apps cannot be developed with Windows 7, Windows Vista, or Windows XP.
Visual Studio project templates give a great jump-start to building HTML and XAML applications. We create a new Visual C# Windows Store Blank App (XAML) project and name it NYTimesBestSeller (see Figure 1-4).
Figure 1-4. Visual Studio templates for XAML
The New York Times Best Sellers app displays the details of the New York Times fiction best sellers in a grid view. Before we go further let’s see the project structure in Figure 1-5.
Figure 1-5. NYTimesBestSeller project structure
In the default project structure, we have created three new folders via Models, Views, and ViewModel. These folders are used for the Models, Views, and ViewModel. Also we moved the MainPage.xaml to the Views folder.
Now, we create the application's data model. This class are created in the Model folders in the C# file BookSellersModel.cs.
The BookSellersModel.cs file implements two classes:
The Book class shown in Listing 1-1 represents details of one of the books on the best sellers list. The details include book title, description, author, and price.
Listing 1-1. Adding Book Class to the Project
public class Book
{
public string Title { get; set; }
public string Description { get; set; }
public string Author { get; set; }
public string Publisher { get; set; }
public double Price { get; set; }
}
The BestSellersModel class shown in Listing 1-2 is an ObservableCollection of Book object. This class loads the New York Times best seller books into the observable class.
Listing 1-2. BestSeller Class to Store the Best Seller Information
public class BestSeller : ObservableCollection<Book>
{
private static BestSeller current = null;
public static BestSeller Current
{
get
{
if (current == null)
current = new BestSeller();
return current;
}
}
private BestSeller()
{
LoadData();
}
public async void LoadData()
{
//Code here to get New York Times best seller
}
}
The New York Times best seller API is called by the LoadData method to get the book details (see Listing 1-3). This API returns a JSON object that will be parsed using the WinRT APIs residing in the Windows.Data.Json namespace.
Listing 1-3. LoadData Method Fetch Data Using the New York Times API
public async void LoadData()
{
string url = "http://api.nytimes.com/svc/books/v2/lists//hardcover-fiction.json?&offset=&sortby=&sortorder=&api-key=76038659ae9258d87cfb6dc8d6f02d35:11:66739421";
HttpResponseMessage response = await client.GetAsync(url);
string jsonData = await response.Content.ReadAsStringAsync();
JsonObject jsonObject = JsonObject.Parse(jsonData);
var resultObject = jsonObject.GetObject();
var result = resultObject["results"].GetArray();
foreach (var item in result)
{
JsonObject bookdetails = item.GetObject().GetNamedValue("book_details").GetArray()[0].GetObject();
Book book = new Book();
book.Title = bookdetails.GetNamedString("title");
book.Description = bookdetails.GetNamedString("description");
book.Author = bookdetails.GetNamedString("author");
book.Price = bookdetails.GetNamedNumber("price");
book.Publisher = bookdetails.GetNamedString("publisher");
Add(book);
}
}
We have used await and the async keyword that was introduced with .NET 4.5 to asynchronously process the network request to avoid GUI locking and freezing. Here the async keyword flags a method as containing asynchronous components, and the await keyword triggers an asynchronous process and resumes execution when it completes without blocking the main thread. We use await and async a lot throughout this book as the entire WinRT framework is built with performance in mind and in WinRT any potential task that takes longer than 50 ms is defined asynchronously. Responsiveness of the app is one of the minimum requirements of the Windows 8 App certification.
The ViewModel is designed to list the best sellers, and we use the FictionBestSellers property to hold the list (see Listing 1-4). Here we create the instance of the Model. Apart from this, ViewModel can also be used to expose various commands by implementing ICommand.
Listing 1-4. MainViewModel works a DataContext for view MainPage.xaml
public class MainViewModel
{
public MainViewModel()
{
}
public BestSeller FictionBestSellers
{
get
{
return BestSeller.Current;
}
}
}
Command objects are derived from the ICommand interface, which has two important methods: The CanExecute method controls whether the corresponding control that is bound to this command is enabled or disabled, and the Execute method specifies the action to be taken once the control is clicked. We see the use of the command object later in this book.
Now that the Model and ViewModel are ready, let’s focus on the View. Let’s use the default page, which is MainPage.xaml. Here we move the page from the root to the Views folder so that we will have a manageable project structure. The page template comes with a Grid where TextBlock is added to showcase the application title and GridView to display data (see Listing 1-5).
Listing 1-5. MainPage.xaml View Defined in the XAML
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<Grid.RowDefinitions>
<RowDefinition Height="9*"/>
<RowDefinition Height="55*"/>
</Grid.RowDefinitions>
<TextBlock
TextWrapping="Wrap"
Text="New York Times Best Sellers"
Margin="60,20,0,20"
FontSize="64"/>
<GridView Grid.Row="1"
Margin="60,0,0,0"
ItemsSource="{Binding FictionBestSellers}"
ItemTemplate="{StaticResource BookDataTemplate}"/>
</Grid>
Visual Studio generates code for us at the OnLaunched event in app.xaml.cs so that MainPage.xaml will be used as the start page of the app (see Listing 1-6).
Listing 1-6. Configuring Application’s Startup Page
protected override void OnLaunched(LaunchActivatedEventArgs args)
{
Frame rootFrame = Window.Current.Content as Frame;
if (rootFrame == null)
{
/* Create a Frame to act as the navigation context and navigate to the first page*/
rootFrame = new Frame();
if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
//TODO: Load state from previously suspended application
}
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
if (rootFrame.Content == null)
{
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
if (!rootFrame.Navigate(typeof(MainPage), args.Arguments))
{
throw new Exception("Failed to create initial page");
}
}
// Ensure the current window is active
Window.Current.Activate();
}
The next step is to create the connection between the View and ViewModel, which is done by creating the instance of the ViewModel in the View’s constructor and setting it to the data context of the page (see Listing 1-7).
Listing 1-7. Connecting View and ViewModel
public MainPage()
{
this.InitializeComponent();
MainViewModel vm = new MainViewModel();
this.DataContext = vm;
}
Data binding is a useful tool in putting an application together and WinRT relies heavily on the usage of data binding. WPF, Silverlight, or Windows Phone developers are mostly familiar with data binding, but for someone who is new to this, we show an example of data binding in The New York Times Best Sellers app.
A data binding consists of a target and a source. The target is usually a property of a control, and the source is usually a property of a data object. In Listing 1-5 we bound the source BestSeller collection to the target control’s ItemsSource property. Also in Listing 1-8 we bind the Book class Title property to the Control Text property.
Before we go further, let’s see how the application looks when it runs for the first time.
If we have a close look at Listing 1-5, we’ll see that the ViewModel FictionBestSellers property is bound to the GridView. GridView along with ListView are two powerful data controls in WinRT that are designed for touch input. Both these controls are derived from ListViewBase and neither adds any properties, methods, or events other than ListView used for vertical scrolling, and GridView for horizontal scroll.
By seeing the app one would notice that the book title, author, and description are formatted nicely and for that to happen GridView needs to know how to display each object in the list, the properties of the object that need to be displayed, and how they should appear. We do this more often with a DataTemplate. Here we create a DataTemplate named BookDataTemplate, which is assigned to the GridView ItemTemplate property as shown in Listing 1-5. The ItemTemplate gets or sets the template for each item and the DataTemplate customizes the appearance of the data. In this case, we created a layout with Border and StackPanel and three TextBlock instances that we bind to the various Book object properties like Title, Author, and Description (see Listing 1-8). The result is shown in Figure 1-6.
Listing 1-8. The BookDataTemplate Is Defined Inside the MainPage.xaml
<DataTemplate x:Key="BookDataTemplate">
<Grid
HorizontalAlignment="Left"
Width="250"
Height="150">
<Border
Background="{StaticResource ListViewItemPlaceholderBackgroundThemeBrush}">
<TextBlock
Text="{Binding Description}"
Foreground="{StaticResource ListViewItemOverlayForegroundThemeBrush}"
Style="{StaticResource TitleTextStyle}"
FontWeight="Normal"
FontSize="13.333"
Margin="10,0"/>
</Border>
<StackPanel
VerticalAlignment="Bottom"
Background="{StaticResource ListViewItemOverlayBackgroundThemeBrush}">
<TextBlock
Text="{Binding Title}"
Foreground="{StaticResource ListViewItemOverlayForegroundThemeBrush}"
Style="{StaticResource TitleTextStyle}"
Height="20"
Margin="15,0,15,0"/>
<TextBlock
Text="{Binding Author}"
Foreground="{StaticResource ListViewItemOverlaySecondaryForegroundThemeBrush}"
Style="{StaticResource CaptionTextStyle}"
TextWrapping="NoWrap"
Margin="15,0,15,5"/>
</StackPanel>
</Grid>
</DataTemplate>
Figure 1-6. Windows 8 Application displaying the New York Times Best Sellers List
Conclusion
This chapter introduced Windows 8 App development and various concepts that are needed to build an XAML-based data-driven Windows 8 App by building our first Windows 8 App. As you can see, this was just a brief introduction to the concepts and frameworks. As you look to move beyond the basics of Windows 8 development, there are many more advanced scenarios that are available, and among them are user-updated data, two-way binding, value converters, and advanced MVVM techniques like passing data between pages, dialog UI, and so forth. In the next chapter we use the MVVM pattern and data binding that we learned in this chapter and will them in building an HTML5 and JavaScript-based Windows 8 application using JavaScript patterns, MVVM, and KnockoutJS.
3.143.254.90