About this book

Windows Store apps are designed to run on various devices such as desktops, tablets, and smart phones, and are available on the Windows Store. Unlike traditional desktop apps, Windows Store apps are full-screen, with a borderless window, and free from distractions.Instant Windows 8 C++ Application Development How-to is a practical guide which includes a series of examples, guidelines, step-by-step instructions, and techniques for C++ developers. You will discover how to build Windows Store apps using C++, all the way from creation to publication. You will discover how to take full advantage of the new style Windows 8 Store app development experience, quickly and painlessly.This book will enable you to build C++ applications that can be submitted to the Windows 8 Store. You will learn how to build Windows Store style UI and features that define the core Windows Store experience, writeWinRT components, and packand deployyour app to the Windows Store.

Publication date:
April 2013
Publisher
Packt
Pages
56
ISBN
9781849695725

 

Chapter 1. Instant Windows 8 C++ Application Development How-to

Welcome to Instant Windows 8 C++ Application Development How-to.

Windows Store style apps are an important addition to the Windows 8 Programming Model, which is designed to run on various devices such as desktops, tablets, and smartphones, and sellable on the Windows Store. Windows Store apps can be developed using various languages, including C#, Visual Basic, and C++.

This book contains a quick and easy way to jump into the world of Windows Store app development using C++. By the end of this book, you will have learned how to build Windows Store style UI and features that define the core Windows Store Experience, writing Windows Runtime components and packaging and deploying your app to the Windows Store.

This book is for experienced C++ developers who want to leverage their C++ skills to build Windows Store apps for Windows 8. In this book you'll learn fundamental concepts and techniques to boost your Windows Store apps development in C++ using language extensions called C++/CX, XAML, and the WinRT libraries.

 

Exploring the Windows 8 architecture (Must know)


The Windows Store style interface introduced in Windows 8 is designed to be a full-screen app tailored to the devices they are run on and personalized for touch interaction and the Windows user interface. It has a brand new look and feel, runs on a variety of devices such as desktops, tablets, and smartphones, and is sellable on the Windows Store.

The Windows 8 architecture is as shown in the preceding diagram. There are a lot of different ways to create Windows Store style applications. Notice that in Windows Store style applications, XAML is connected to both C++ and C#/VB; this means that designers can make the interface in Expression Blend and can use native C++ as code behind the scenes.

In addition to this, Windows 8 allows you to leverage your existing skills, and apps can be developed in a variety of languages.

  • Web developers can use their HTML5, CSS3, and JavaScript skills

  • .NET, WPF, or Silverlight developers can use XAML with code-behind in C++, C#, or Visual Basic skills

  • DirectX developers can develop using native C++ and HLSL to take full advantage of graphics hardware

Windows Runtime (Win RT) is a set of APIs used to build Windows Store apps. Win RT APIs are available to all supported languages, including JavaScript, C++, C#, and Visual Basic. Win RT APIs are accessible to other Microsoft programming frameworks, such as the .NET Framework or Windows C Runtime Library. Traditional Windows desktop apps can also access a new Win RT functionality, in addition to the proven Win32 and .NET APIs.

Getting ready

The tools and resources you require are as follows:

  • Windows 8, as Windows Store apps run only on Windows 8.

  • The Windows SDK provides a complete development environment. The Windows 8 SDK is free to download and packaged with Visual Studio Express 2012 for Windows 8 and Expression Blend for Microsoft Visual Studio 2012, for your development.

  • Visual Studio 2012 helps developers to write, debug, package, and deploy Windows Store app code.

  • Expression Blend is a designing tool for creating a great-looking user interface for your Windows Store app. Visual Studio and Expression Blend are designed to help developers and designers to work together on the same code without interfering in each other's work. Developers and designers can switch their solution files back and forth.

  • A Microsoft account is required to download/upload apps from/to the Windows Store.

  • Developer licenses allow you to install, develop, test, and evaluate Windows Store apps and certify them. Developer licenses are free, and if you already have a Microsoft account you can obtain as many licenses as you require.

How to do it...

Perform the following steps:

  1. Download Windows 8 and install it on your system.

  2. Download Windows SDK 8 and install Visual Studio 2012 and Expression Blend, which are packaged with Windows SDK.

  3. Now a developer license is required. Get a developer license through Visual Studio.

  4. When you run Microsoft Visual Studio 2012 on your local machine for the first time, you are prompted to obtain a developer license. Read the license terms, and then click on I Agree. In the User Account Control (UAC) dialog box, click on Yes to continue.

    If you already have a Microsoft account, log in by providing your credentials. Once you sign in, the developer license is ready for you and the Developer License dialog box will display the expiry date as well; you need to renew the license before it expires.

    If you do not have a Microsoft account, click on the Sign up link from the Developer License dialog box and open a Microsoft account; then come back to get the developer license.

    You can renew the developer license before it expires through the Visual Studio IDE. If you are using the Visual Studio 2012 Express Edition, go to Store | Acquire Developer License. Otherwise, go to Project | Store | Acquire Developer License.

 

Building your first app (Must know)


In the previous recipe, we learned the fundamentals of Windows Store style apps. This recipe will teach you how to write your first HelloWorld Windows Store style app.

Getting ready

Please refer to the HelloWorld project for the full working code of this recipe.

How to do it...

To start creating a HelloWorld app, first create a C++ Windows Store app. Here we use the most basic project template, Blank App (XAML). To create a Windows Store app project, follow these steps:

Launch Visual Studio 2012 for Windows 8. The Visual Studio 2012 for Windows 8 start screen appears. If it has been launched for the first time, set the development settings for the Visual C++ environment when prompted.

  1. On the menu bar, go to File | New Project. The New Project dialog appears. The left pane of the dialog lets you select the type of templates to display.

  2. On the left pane, expand Installed and then expand Visual C++ and select the Windows Store template type. The dialog's center pane displays a list of project templates for Windows Store apps.

  3. On the center pane, select Blank App (XAML). Enter the name for the project as HelloWorld.

  4. Click on the OK button. Your Blank App (XAML) project files are created.

  5. At the top of the Solution Explorer pane, choose the Show All Files icon to show all the created project file templates. The following screenshot shows all the project files that the Blank App (XAML) template has created.

  6. Let's first look at the project files that are generated. A few files can be modified and the others cannot be edited.

Filename

Description

Editable

App.xaml

MainPage.xaml

App.xaml and MainPage.xaml define the user interface for your app. These files can be modified by using the Visual Studio Code Editor, Microsoft Expression Blend, or any XAML editor tool.

Yes.

App.xaml.h

App.xaml.cpp

MainPage.xaml.h

MainPage.xaml.cpp

The .h and .cpp are header-specific and code-behind files. The MainPage.xaml.h and MainPage.xaml.cpp files are where you add the logic that is related to this page. The App.xaml.h and App.xaml.cpp files are where you add the logic that is scoped throughout your app.

Yes.

Package.appxmanifest

Package.appxmanifest is a metadata file that describes your application information, such as display name, description, logos, and capabilities. This file can be edited in Manifest Designer.

Yes.

*.png

There are several *.png files that are present under the Asset folder. These image files represent the default logo and splash-screen images that you can replace with your own later.

Yes.

pch.h

pch.cpp

These are C++ precompiled header files. #include directives can be added to the pch.h file as needed.

Yes.

App.g.h

App.g.hpp

These files are generated by Visual Studio 2012 automatically. App.g.hpp contains the main entry code for Windows Store apps, while App.g.h is responsible for loading .xaml files into the memory at runtime.

No.

Even if the files are modified, the files are overwritten while navigating from page or building your app.

StandardStyles.xaml

StandardStyles.xaml defines the styles and templates used by the project.

Don't modify this file directly; however, you can copy and give it a different name and then modify it for your use.

MainPage.g.h

MainPage.g.hpp

MainPage.g.h and MainPage.g.hpp contain the partial implementation of the classes MainPage and App, and are generated automatically everytime when we modify and save the MainPage.xaml file.

No.

XamlTypeInfo.g.cpp

It's a metadata file that implements the binding behavior for interacting with XAML.

No.

To modify the start page to say "Hello World", perform the following steps:

  1. Double-click on MainPage.xaml in Solution Explorer to open it in the XAML Editor.

  2. In the root grid, add the TextBlock object; the following is the XAML we now have. Name the control as HelloWorldTextBlock and set FontSize to 50.

    <Page
      x:Class="HelloWorld.MainPage"
      xmlns="http://schemas.microsoft.com/
      winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:local="using:HelloWorld"
      xmlns:d="http://schemas.microsoft.com/
      expression/blend/2008"
      xmlns:mc="http://schemas.openxmlformats.org/
      markup-compatibility/2006"
      mc:Ignorable="d">
    
      <Grid Background=
        "{StaticResource ApplicationPageBackgroundThemeBrush}">
        <TextBlock x:Name=
        "HelloWorldTextBlock" FontSize="50"></TextBlock>
      </Grid>
    </Page>

    Tip

    Downloading the example code

    You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

  3. Now navigate to the file MainPage.xaml.cpp; this is where we can set the TextBlock text. TextBlock is actually a pointer, but you do not have to worry about disposing of it because it will be automatically removed once its context has been exited. When you compile your solution, the XAML will also be compiled to C++, just like the XAML in a normal .NET application is compiled.

  4. To set the value of TextBlock, use the following code:

    MainPage::MainPage()
    {
      InitializeComponent();
      HelloWorldTextBlock->Text = "Hello, World";
    }
  5. Press the F5 key to run the app. Hello, World is displayed as output.

How it works...

In this recipe, you learned how to create a simple HelloWorld app. A default splash screen that appears is defined by an image, splashscreen.png, and a background color is specified in the app's manifest file. The splash screen vanishes after some time, and then the HelloWorld app emerges. It is surrounded by a black screen with the title "Hello World".

Go to the start screen by pressing the Windows key, then scroll to the end of the start screen and you will notice that the app is deployed and the app tile is added to the last group on the start screen.

To run the HelloWorld app again, tap or click on the tile in the start screen, or press the F5 key in Visual Studio 2012 to run it in the debugging mode.

 

Creating a Windows 8 tile app (Must know)


The start screen is the main place to launch applications in Windows 8. The tiles on the start screen are application shortcuts; click on one of them to launch your application.

Getting ready

Please refer to the project HelloWorld under 5725OT_03_Code for the full working code of this recipe.

How to do it...

Perform the following steps for creating a Windows 8 tile app:

  1. Open the HelloWorld project from the Building your first app (Must know) recipe.

  2. Open the Manifest Editor and double-click on package.appxmanifest. This opens the Manifest Editor window.

  3. Supply the tile details.

    1. Prepare an image file, 150 px x 150 px, to be displayed on the tile.

    2. Prepare a small version of that image file, 30 px x 30 px. This image is used in search results, the All Programs list, and other places in the UI.

    3. Select the Application UI pane from the Manifest Editor, if it is not already open.

    4. Replace the default images with paths to your own logo images as shown in the following screenshot:

    5. Choose whether to show the app's short name on the tile. This name should be 13 characters or less. If the name is too long, it will be truncated. You can elect to show the logo, the name, or neither.

    6. Choose whether the name's text should use a light or dark font, based on the background color.

    7. Either accept the default background color or provide your own as a W3DC color string (for example, #FFFFFF).

How it works...

To debug the app and then run it, press the F5 key or go to Debug | Start Debugging. To run the app without debugging, press Ctrl + F5 or go to Debug | Start Without Debugging. Switch to your start screen and scroll to the right to see if the Hello, World tile appears on the start screen. Click on the Hello, World tile to launch the application.

 

Exploring app contracts and extensions (Should know)


Contracts and extensions are used by Windows Store apps; they enable the interactions with other running applications.

Contracts are agreements between one or more applications while extensions are agreements between apps and Windows.

The Search contract is an example of a contract. By implementing the Search contract, users can not only search for the content of their apps, but can also search for content from other apps.

AutoPlay extensions enable your app to be listed as an AutoPlay choice when a device is connected to your system.

Getting ready

Please refer to the SearchContract project for the full working code to add search suggestions to your application.

How to do it...

You can enhance your application by adding the search experience to provide suggestions as the user types a search term into the search box. For this, you need to register a handler for SuggestionsRequested events. Here's how:

  1. Launch Visual Studio 2012 for Windows 8. The Visual Studio 2012 for Windows 8 start screen appears. If it has been launched for the first time, set the development settings for the Visual C++ environment when prompted.

  2. On the menu bar, go to File | New Project. The New Project dialog appears. The left pane of the dialog lets you select the type of templates to display.

  3. On the left pane, expand Installed and then expand Visual C++ and select the Windows Store template type. The dialog's center pane displays a list of project templates for Windows Store apps.

  4. On the center pane, select Blank App (XAML).

  5. Enter the name for the project as SearchContract.

  6. Right-click on the project in Solution Explorer and go to Add | New Item to add a Search contract named SearchResultsPage.xaml.

  7. On the <Pages.Resources> section of SearchResultsPage.xaml, change My Application to Search in the string resource named AppName to change the title at the top of the page.

    XAML
    <x:String x:Key="AppName">Search</x:String>
  8. Open App.xaml.cpp and add the following using statement at the top of the file:

    using namespace std;
    using namespace Windows::ApplicationModel::Search;
  9. Add the following statements to the beginning of the OnLaunched method, before Window::Current->Content = rootFrame:

    // Register handler for SuggestionsRequested events from //the search pane
    SearchPane^ searchPane = SearchPane::GetForCurrentView();
    searchPane->SuggestionsRequested += ref new TypedEventHandler<SearchPane^, SearchPaneSuggestionsRequestedEventArgs^>(this, &App::OnSearchPaneSuggestionsRequested);
  10. Now add the following method to the Application class.

    void App::OnSearchPaneSuggestionsRequested(SearchPane^ sender, SearchPaneSuggestionsRequestedEventArgs^ e)
    {
    static wstring suggestionList [] =
      {
    L"shanghai", L"istanbul", L"karachi", L"delhi", L"mumbai", L"moscow", L"sãopaulo", L"seoul", L"beijing", L"jakarta", L"tokyo", L"mexico city", L"kinshasa", L"newyork city", L"lagos", L"london", L"lima", L"bogota", L"tehran", L"ho chi minh city", L"hongkong", L"bangkok", L"dhaka", L"cairo", L"hanoi", L"rio de janeiro", L"lahore", L"chonquing", L"bengaluru", L"tianjin", L"baghdad", L"riyadh", L"singapore", L"santiago", L"saintpetersburg", L"surat", L"chennai", L"kolkata", L"yangon", L"guangzhou", L"alexandria", L"shenyang", L"hyderabad", L"ahmedabad", L"ankara", L"johannesburg", L"wuhan", L"losangeles", L"yokohama",L"abidjan", L"busan", L"cape town", L"durban", L"pune", L"jeddah", L"berlin", L"pyongyang", L"kanpur", L"madrid", L"jaipur",L"nairobi", L"chicago", L"houston", L"philadelphia", L"phoenix", L"sanantonio", L"sandiego", L"dallas", L"sanjose",L"jacksonville", L"indianapolis", L"sanfrancisco", L"austin", L"columbus", L"fort worth", L"charlotte", L"detroit",L"elpaso", L"memphis", L"baltimore", L"boston", L"seattlewashington", L"nashville", L"denver", L"louisville", L"milwaukee",L"portland", L"lasvegas", L"oklahoma city", L"albuquerque", L"tucson", L"fresno", L"sacramento", L"long beach", L"kansas city",L"mesa", L"virginia beach", L"atlanta", L"colorado springs", L"omaha", L"raleigh", L"miami", L"cleveland", L"tulsa", L"oakland",            L"minneapolis", L"wichita", L"arlington", L"bakersfield", L"neworleans", L"honolulu", L"anaheim", L"tampa", L"aurora", L"santaana", L"st. louis", L"pittsburgh", L"corpuschristi", L"riverside", L"cincinnati", L"lexington", L"anchorage",L"stockton", L"toledo", L"st. paul", L"newark", L"greensboro", L"buffalo", L"plano", L"lincoln", L"henderson", L"fortwayne", L"jersey city", L"st. petersburg", L"chula vista", L"norfolk", L"orlando", L"chandler", L"laredo", L"madison", L"winston-salem",L"lubbock", L"baton rouge", L"durham", L"garland", L"glendale", L"reno", L"hialeah", L"chesapeake", L"scottsdale", L"northlasvegas", L"irving", L"fremont", L"irvine", L"birmingham", L"rochester", L"sanbernardino", L"spokane",L"toronto", L"montreal", L"vancouver", L"ottawa-gatineau", L"calgary", L"edmonton", L"quebec city", L"winnipeg", L"hamilton"
      };
      autoqueryText = e->QueryText;
      wstring query = wstring(queryText->Data());
      // convert query string to lower case.
      transform(query.begin(), query.end(), query.begin(), 
      tolower);
    
      auto request = e->Request;
      for each(wstring suggestion in suggestionList)
        {
          if (suggestion.find(query) == 0)
            {
            // if the string starts with the queryText 
            (ignoring case), add suggestion to search pane.
            request->SearchSuggestionCollection-
            >AppendQuerySuggestion(ref new 
            String(const_cast<wchar_t*>(suggestion.c_str())));
    
        }
      }
    }
  11. To run the app, press the F5 key or deploy it.

  12. Display the charms (charms can be displayed by pressing the Windows key + C).

  13. Tap the Search charm to display the Search pane.

  14. Type san into the Search box. Verify that the code you just added provides search suggestions for words that match the pattern and these suggestions appear in the suggestion list underneath the Search box, as shown in the following screenshot:

  15. Verify that you get the following suggestions starting from the san text typed in the Search box:

    • santiago

    • san antonio

    • san diego

    • san jose

    • san francisco

  16. Press Alt + F5 to stop the app or return to Visual Studio and stop debugging.

How it works...

A Search contract enables your application to connect to the operating system's search system. For providing search suggestions, you can register for the SuggestionsRequested event and build your own list of suggestions.

The SuggestionsRequested event is fired when the app is required to show new suggestions matching the user's query text or when the user changes the query text in the Search pane. Suggestions may arrive from three sources: search history, local files, or from a source specified by the app.

public: eventTypedEventHandler<SearchPane, SearchPaneSuggestionsRequestedEventArgs>^ SuggestionsRequested {
   Windows::Foundation::EventRegistrationToken add(TypedEventHandler<SearchPane, SearchPaneSuggestionsRequestedEventArgs>^ value);
void remove(Windows::Foundation::EventRegistrationToken token);}
 

Creating asynchronous operations (Should know)


Asynchronous programming enables apps to continue to be responsive to user input without disturbing the main flow of the program. The long-running tasks remain in the background without disturbing the other system operations, and you receive the results later. You receive the progressive notifications for if the task is cancelled or is running. By using Windows Runtime asynchronous APIs, your code consistently makes unblocked calls and threads need not be managed explicitly.

Some examples of Windows Runtime asynchronous API's tasks are displaying a dialog box, accessing files, data retrieval from the Internet, and so on.

In this recipe, you will learn how to write asynchronous operations for file access.

Getting ready

Please refer to the FileAccess project for the full working code to create asynchronous operations for file access.

How to do it...

Perform the following steps for writing asynchronous operations for file access:

  1. Create a blank solution and name it as FileAccess.

  2. Open the pch.h file and add the following code at the end of the file.

    #include<ppltasks.h>
  3. Open MainPage.xaml and add the following XAML code right after <Grid Background="{StaticResourceApplicationPageBackgroundThemeBrush}">:

    <Grid.ColumnDefinitions>
      <ColumnDefinition Width="124"/>
      <ColumnDefinition/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
      <RowDefinition Height="120"/>
        <RowDefinition Height="Auto" MinHeight="145"/>
      <RowDefinition/>
    </Grid.RowDefinitions>
    <TextBlockHorizontalAlignment="Left" TextWrapping="Wrap" VerticalAlignment="Top" Grid.Column="1" Margin="10,41,0,0" Height="38" Width="316" FontSize="32" Text="File Access"/>
    <Button x:Name="CreateFileButton" Content="Create File" HorizontalAlignment="Left" VerticalAlignment="Top" Grid.Column="1" Margin="10,10,0,0" Grid.Row="1" Height="39" Width="204" Click="CreateFileButton_Clicked"/>
    <Button x:Name="ReadFileButton" Content="Read From File" HorizontalAlignment="Left" VerticalAlignment="Top" Grid.Column="1" Margin="10,54,0,0" Grid.Row="1" Height="39" Width="204" Click="ReadFileButton_Clicked"/>
    <Button x:Name="WriteFileButton" Content="Write To File" HorizontalAlignment="Left" VerticalAlignment="Top" Grid.Column="1" Margin="302,109,0,0" Grid.Row="2" Height="39" Width="204" Click="WriteFileButton_Clicked"/>
    <TextBlockGrid.Column="1" HorizontalAlignment="Left" Height="10" Margin="249,25,0,0" Grid.Row="1" TextWrapping="Wrap" Text="Status" VerticalAlignment="Top" Width="37"/>
    <TextBlock x:Name="StatusTextBlock" TextWrapping="Wrap" Text="" Grid.Column="1" Margin="302,25,123,9" Grid.Row="1" Foreground="#FF2118E8" LineStackingStrategy="BlockLineHeight"/>
    <TextBox x:Name="InputTextBox" Grid.Column="1" Height="94" Margin="302,10,123,0" Grid.Row="2" TextWrapping="Wrap" VerticalAlignment="Top"/>
    <TextBlockGrid.Column="1" HorizontalAlignment="Left" Height="37" Margin="249,10,0,0" Grid.Row="2" TextWrapping="Wrap" Text="Input Text" VerticalAlignment="Top" Width="48"/>

    The XAML UI contains buttons for creating a file, writing into the file, and reading the file asynchronously.

  4. Create the CreateFileButton_Clicked event for the click of a button, the ReadFileButton_Clicked event for reading from a file, and the WriteFileButton_Clicked event for writing to a file, as shown in the preceding code snippet.

  5. Open the file MainPage.xaml.h and add the following code in the private section:

    Windows::Storage::StorageFile^ sampleFile;

    Now add the following two properties in the public section. One is for the filename and the second is for the StorageFile object. This object will be used throughout the application to access the same files for writing and reading purposes.

    static property Platform::String^ Filename
      {
        Platform::String^ get()
        {
          return ref new 
          Platform::String(L"fileAccessSample.txt");
        }
      }
    
    property Windows::Storage::StorageFile^ SampleFile
      {
        Windows::Storage::StorageFile^ get()
        {
          returnsampleFile;
        }
        void set(Windows::Storage::StorageFile^ value)
        {
          sampleFile = value;
        }
      }
  6. Open MainPage.xaml.cpp and add the following namespaces at the top:

    using namespace concurrency;
    using namespace Windows::Storage;
  7. Now write the code for creating a file, writing to the file, and reading the file, as follows:

    voidMainPage::CreateFileButton_Clicked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
    {
      StorageFolder^ temporaryFolder = 
      ApplicationData::Current->LocalFolder;
    
      create_task(temporaryFolder->CreateFileAsync
      (Filename, CreationCollisionOption::ReplaceExisting)).
      then([this](StorageFile^ file)
      {
        this->SampleFile = file;
        StatusTextBlock->Text = "The file '" + file->Name + "' 
        was created at path " + file->Path;
      });
    }
    
    voidMainPage::ReadFileButton_Clicked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
    {
      StorageFile^ file = this->SampleFile;
      if (file != nullptr)
      {
        create_task(FileIO::ReadTextAsync(file)).then([this, 
        file](String^ fileContent)
        {
          StatusTextBlock->Text = "The following text is read 
          from '" + file->Name + " at path " + file->Path + 
          "':\n\n" + fileContent;
        });
      }
    }
    
    void MainPage::WriteFileButton_Clicked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
    {
      StorageFile^ file = this->SampleFile;
      if (file != nullptr)
      {
        String^ userText = InputTextBox->Text;
        if (userText != nullptr&& !userText->IsEmpty())
        {
          create_task(FileIO::WriteTextAsync(file, 
          userText)).then([this, file, userText]()
          {
            StatusTextBlock->Text = "The following text is 
            written to '" + file->Name + " at path " + 
            file->Path + "':\n\n" + userText;
          });
        }
        else
        {
          StatusTextBlock->Text = 
          "The input textbox is empty, please write 
          something and then click 'Write' again.";
        }
      }
    }
  8. Press the F5 key to start the app. The following screen will be displayed:

    First click on the Create File button; the fileAccessSample.txt file will be created. Now type something into the textbox and click on the Write To File button; the input text will be written to the file. Clicking on Read From File will read the content from the file as shown in the preceding screenshot.

  9. Now return to Visual Studio and stop debugging.

How it works...

The preceding sample shows how to create, read from, and write into a file. This sample uses Windows->StorageAPIs.

  • Creating a file in the application folder: Uses StorageFolder->CreateFileAsync(String, CreationCollisionOption) to create a file in the folder, and an option to overwrite it if it exists

  • Writing into and reading content from a file: The FileIO->WriteTextAsync and FileIO->ReadTextAsync methods are used to write into a file and read the content from a file

 

Writing connected apps (Become an expert)


A connected (or network-aware) app in the Windows Store is defined as an app that uses the network for any purpose. The apps can use networking for purposes including RSS feeds, games, and to interact with nearby devices. For example, multiplayer games over the Internet require you to connect to a network and discover online players to play with. Another example is when your app might require you to connect to REST-based services, which require you to connect to some network.

To write connected apps, you need to provide the appropriate network capabilities and use the right APIs for connection. To support modern app lifecycle scenarios, your app should handle connections as background tasks. In case of your apps stumbling upon network-related errors, you should know where to start troubleshooting your app. So your app should establish the secure network connections and troubleshoot them.

In this recipe you will learn to add support for the networking of your app.

Getting ready

Please refer to the LiveConnect project for the full working code to create an app that will connect to Microsoft Account and display user profile information using Rest API.

How to do it...

Perform the following steps for writing connected apps:

  1. Launch Visual Studio 2012 and create a new project.

  2. Expand Visual C++ from the left pane and then select the node for Windows Store apps.

  3. Select the Blank (XAML) template and then name the project as LiveConnect.

  4. Open MainPage.Xaml and add the following code into it:

    <Grid x:Name="LayoutRoot" Background="Black">
      <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
      </Grid.RowDefinitions>
      <Grid x:Name="Input" Grid.Row="0">
        <Grid.RowDefinitions>
          <RowDefinition Height="Auto"/>
          <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <TextBlock x:Name="InputTextBlock1" Grid.Row="0" 
        TextWrapping="Wrap" Style=
        "{StaticResourceBasicTextStyle}" 
        HorizontalAlignment="Left">
          <Run Text="This sample demonstrates how to call "/>
          <Run FontWeight="Bold" 
          Text="Windows.Security.Authentication.OnlineId "/>
          <Run Text="Login to Microsoft Account using REST Live 
          Connect service."/>
        </TextBlock>
        <StackPanel Orientation="Horizontal" Grid.Row="1">
          <Button x:Name="SignInButton"  Content="Sign In" 
          Margin="0,0,10,0" Click="SignInButton_Click" 
          IsEnabled="{Binding NeedsToGetTicket}"/>
          <Button x:Name="SignOutButton"  Content="Sign Out"  
          Margin="0,0,10,0" Click="SignOutButton_Click" 
          IsEnabled="{Binding CanSignOut}"/>
        </StackPanel>
      </Grid>
    
      <Grid x:Name="Output" HorizontalAlignment="Left" 
      VerticalAlignment="Top" Grid.Row="1">
        <Grid.ColumnDefinitions>
          <ColumnDefinition Width="Auto"/>
          <ColumnDefinition Width="Auto"/>
        </Grid.ColumnDefinitions>
        <TextBlock Style="{StaticResourceBasicTextStyle}" 
        Grid.Row="1" Grid.Column="0"  Margin="0,0,10,0" >
        Server response:</TextBlock>
        <TextBlock x:Name="ResultText"  Grid.Row="1" 
        Grid.Column="1" TextWrapping="Wrap" 
        Style="{StaticResourceBasicTextStyle}" />
      </Grid>
    </Grid>
  5. Copy the HttpRequest.cpp and HttpRequest.h files from the LiveConnect directory and paste them in your current project directory to include in your project.

  6. Open pch.h and add the following lines:

    #include <msxml6.h>
    #include <collection.h>
    #include <ppltasks.h>
    #include <wrl.h>
    #include "App.xaml.h"
    #include <sstream>
  7. Right-click on the LiveConnect project and choose Properties. Navigate to Configuration Properties | Linker | Input and add shcore.lib and msxml6.lib as dependencies.

  8. Open MainPage.xaml.h and add the following #include directive and the namespace:

    #include "HttpRequest.h"
    
    using namespace Windows::Foundation;
  9. Open MainPage.xaml.h and add the following code:

    public:
    
      property Platform::String^ AccessTicket
      {
        Platform::String^ get()
        { 
          returnaccessTicket;
        }
    
        void set(Platform::String^ value)
        {
          accessTicket = value;
        }
      }
    
      property bool NeedsToGetTicket
        {
          bool get()
          { 
            returnaccessTicket == "";
          }
        }
    
        property bool CanSignOut
        {
          bool get()
          { 
            return authenticator->CanSignOut; 
          }
        }
    
        protected:
    
        virtual void OnNavigatedTo
        (Windows::UI::Xaml::Navigation::
        NavigationEventArgs^ e) override;
    
        private:
    
        Windows::Security::Authentication::OnlineId::
        OnlineIdAuthenticator^ authenticator;
        MainPage^ rootPage;
        Platform::String^ accessTicket;
        Web::HttpRequesthttpRequest;
        concurrency::cancellation_token_
        sourcecancellationTokenSource;
    
        voidSignInButton_Click(Platform::Object^ sender, 
        Windows::UI::Xaml::RoutedEventArgs^ e);
        voidSignOutButton_Click(Platform::Object^ sender, 
        Windows::UI::Xaml::RoutedEventArgs^ e);
      };
    }
  10. Open MainPage.xaml.cpp and add the following namespace at the top:

    using namespace concurrency;
    using namespace Platform;
    using namespace Windows::Security::Authentication::OnlineId;
    using namespace Windows::UI::Xaml;
    using namespace Windows::UI::Xaml::Controls;
    using namespace Windows::UI::Xaml::Navigation;
  11. Now locate OnNavigatedTo and add the following code:

    authenticator = ref new OnlineIdAuthenticator();
    AccessTicket = "";
    SignOutButton->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
  12. Locate the SignInButton_Click function and add the code inside the function. This function runs when we click on the Sign In button on the screen.

    ResultText->Text = "Signing in...";
    AccessTicket = "";
    SignInButton->Visibility = Windows::UI::Xaml::Visibility::Collapsed;
    
        // the ticket requests specifies the Target scopes and 
        the Policy, 
        // which must be configured per application with 
        authentication service provider.
    auto request = ref new OnlineIdServiceTicketRequest("wl.basicwl.contacts_photoswl.calendars", "DELEGATION");
    
        // authenticate user and get the ticket for the 
        requested target
        create_task(authenticator->
        AuthenticateUserAsync(request)).
        then([this](task<UserIdentity^>userIdentity)
        {
          SignOutButton->Visibility = 
          Windows::UI::Xaml::Visibility::Collapsed;
          try
          {
            // .get() will throw if the operation failed
            OnlineIdServiceTicket^ ticket = 
            userIdentity.get()->Tickets->GetAt(0);
            if (ticket->ErrorCode == S_OK)
            {
              AccessTicket = ticket->Value;
            }
            SignInButton->Visibility = 
            Windows::UI::Xaml::Visibility::Collapsed;
            ResultText->Text = "Signed in.";
          }
          catch (consttask_canceled&)
          {
            SignInButton->Visibility = 
            Windows::UI::Xaml::Visibility::Visible;
              // programmatic cancel or in the case of this API 
              user dismiss as well.
              ResultText->Text = "Canceled by user or 
              programmatic cancel.";
              throw; // propagate the task_canceled exception, 
              it will be ignored by the runtime.
            }
    
            autouri = ref new 
            Uri("https://apis.live.net/v5.0/me?access_token=" + 
            AccessTicket);
            cancellationTokenSource = 
            cancellation_token_source();
    
            // Do an asynchronous GET.  We need to use 
            use_current() with the continuations since the 
            tasks are completed on
            // background threads and we need to run on the UI 
            thread to update the UI.
            returnhttpRequest.GetAsync
            (uri, cancellationTokenSource.get_token());
          }).then([this](task<std::wstring> response)
          {
            SignOutButton->Visibility = CanSignOut ? 
            Windows::UI::Xaml::Visibility::Visible : 
            Windows::UI::Xaml::Visibility::Collapsed;
            try
            {
              // .get() will throw if the operation failed
              std::wstringhttpResponse = response.get();
              ResultText->Text = 
              ref new String(httpResponse.c_str());
            }
            catch (consttask_canceled&)
            {
              ResultText->Text = "Request canceled.";
            }
            catch (Exception^ ex) 
            {
              ResultText->Text = 
              "HTTP Exception: " +  ex->Message;
            }
            // schedule this back to the UI thread to enable 
            access to UI elements.
        }, task_continuation_context::use_current());
  13. Locate the SignOutButton_Click function and add the following code inside the function. This function runs when we click on the Sign Out button on the screen.

    AccessTicket = "";
    
    if (CanSignOut)
        {
          ResultText->Text = "Signing out...";
          SignOutButton->Visibility = 
          Windows::UI::Xaml::Visibility::Collapsed;
    
          create_task(authenticator->SignOutUserAsync()).
          then([this]()
          {
            ResultText->Text = "Signed out.";
    
            SignInButton->Visibility = NeedsToGetTicket ? 
            Windows::UI::Xaml::Visibility::Visible : 
            Windows::UI::Xaml::Visibility::Collapsed;
            SignOutButton->Visibility = CanSignOut ? 
            Windows::UI::Xaml::Visibility::Visible : 
            Windows::UI::Xaml::Visibility::Collapsed;
          });
        }
        else
        {
          ResultText->Text = "User can't sign out from 
          Application.";
        }
  14. Press the F5 key to run the application.

  15. Click on the Sign In button, provide your Microsoft Account credentials, and log in.

  16. If you are running it for the first time, you will receive an error message as follows:

    The application requesting authentication tokens is either disabled or incorrectly configured.

    The reason is that you need to register this app with Windows Live before you can begin building it. You can register your app by going to https://appdev.microsoft.com/StorePortals/en-us/account/signup/startand register your app.

How it works...

Here we use the HttpClient class, which provides a base class for sending HTTP requests and receiving HTTP responses from a resource identified by a URI.

This class can send the following requests:

  • GET: Returns a representation of a resource

  • PUT: Updates a resource at the location pointed by the URL or creates a new resource, if it doesn't exist

  • POST: Adds a new resource to a collection

  • DELETE: Deletes a resource

  • And other requests to a web service

Each of these requests is sent as an asynchronous operation, for example, the GetAsync method.

There's more...

This recipe uses Windows Live services to sign in to and sign out from Windows Live Account. Windows services are offered as web services that provide developers with a way to use Windows Live Messenger, Windows Live Mail, SkyDrive, and so on, through a browser. In this section, you will learn how to register your application to use Live Services.

Please follow the instructions on MSDN to register your application to be used as Live Services (http://msdn.microsoft.com/en-us/library/windows/apps/jj841123.aspx).

 

Building WinRT components to be consumed from any language (Become an expert)


Windows Runtime or WinRT is an application architecture on Windows 8 that supports development in C++/CX, C#, VB.NET, as well as JavaScript.

A WinRT component is a DLL and is designed to be called from any WinRT-compliant language, such as C++, C#, VB.NET, and Javascript.

In case your C++ component uses a third-party library or you want to re-use some of your code written in C# or VB.NET, you can wrap all the functionality in a WinRT component and refer it from JavaScript or any other language of your choice.

In this recipe, we will learn to create a WinRT component and call it from JavaScript.

Getting ready

Please refer to the WinRTCalculator project for the full working code to create a WinRT component and consume it in Javascript.

How to do it...

Perform the following steps to create a WinRT component and consume it in Javascript:

  1. Launch Visual Studio 2012 and create a new project.

  2. Expand Visual C++ from the left pane and then select the node for Windows Store apps.

  3. Select the Windows Runtime component and then name the project as WinRTCalculator.

  4. Open Class1.h and add the following method declarations:

    double ComputeAddition(double num1, double num2);
    double ComputeSubstraction(double num1, double num2);
    double ComputeMultiplication(double num1, double num2);
    double ComputeDivision(double num1, double num2);
  5. Open Class1.cpp and add the following method implementations:

    double Class1::ComputeAddition(double num1, double num2)
    {
      return num1+num2;
    }
    
    double Class1::ComputeSubstraction(double num1, double num2)
    {
      if(num1>num2)
        return num1-num2;
      else return num2-num1;
    }
    
    double Class1::ComputeMultiplication(double num1, double num2)
    {
      return num1*num2;
    }
    
    double Class1::ComputeDivision(double num1, double num2)
    {
      if (num2 !=0)
      {
        return num1/num2;
      }
      else return 0;
    }
  6. Now save the project and build it.

Now we need to create a Javascript project where the preceding WinRTCalculator component will be consumed. To create the Javascript project, follow these steps:

  1. Right-click on Solution Explorer and go to Add | New Project.

  2. Expand JavaScript from the left pane, and choose Blank App.

  3. Name the project as ConsumeWinRTCalculator.

  4. Right-click on ConsumeWinRTCalculator and set it as Startup Project.

  5. Add a project reference to WinRTCalculator, as follows:

    1. Right-click on the ConsumeWinRTCalculator project and choose Add Reference.

    2. Go to Solution | Projects from the left pane of the References Manager dialog box.

    3. Select WinRTCalculator from the center pane and then click on the OK button.

  6. Open the default.html file and add the following HTML code in the body:

    <p>Calculator from javascript</p>
    
      <div id="inputDiv">
        <br /><br />
        <span id="inputNum1Div">Input Number - 1 : 	</span>
        <input id="num1" />
        <br /><br />
        <span id="inputNum2Div">Input Number - 2 : 	</span>
        <input id="num2" />
         <br /><br />
        <p id="status"></p>
      </div>
      <br /><br />
      <div id="addButtonDiv">
        <button id="addButton" onclick=
        "AdditionButton_Click()">Addition of Two Numbers
        </button>
      </div>
      <div id="addResultDiv">
        <p id="addResult"></p>
      </div>
      <br /><br />
      <div id="subButtonDiv">
        <button id=
        "subButton" onclick="SubsctractionButton_Click()">
        Substraction of two numbers</button>
      </div>
      <div id="subResultDiv">
        <p id="subResult"></p>
      </div>
         <br /><br />
      <div id="mulButtonDiv">
        <button id=
        "mulButton" onclick="MultiplicationButton_Click()">
        Multiplcation of two numbers</button>
      </div>
      <div id="mulResultDiv">
        <p id="mulResult"></p>
      </div>
      <br /><br />
      <div id="divButtonDiv">
        <button id=
        "divButton" onclick="DivisionButton_Click()">
        Division of two numbers</button>
      </div>
      <div id="divResultDiv">
        <p id="divResult"></p>
      </div>
  7. Open the default.css style file from 5725OT_08_Code\WinRTCalculator\ConsumeWinRTCalculator\css\ default.css and copy-paste the styles to your default.css style file.

  8. Add JavaScript event handlers that will call the WinRTCalculator component DLL. Add the following code at the end of the default.js file:

    var nativeObject = new WinRTCalculator.Class1();
    
    function AdditionButton_Click() {
      var num1 = document.getElementById('num1').value;
      var num2 = document.getElementById('num2').value;
      if (num1 == '' || num2 == '') {
        document.getElementById('status').innerHTML = 
        'Enter input numbers to continue';
      }
      else {
        var result = nativeObject.computeAddition(num1, num2);
        document.getElementById('status').innerHTML = '';
        document.getElementById('addResult').innerHTML = 
    result;
      }
    }
    
    function SubsctractionButton_Click() {
      var num1 = document.getElementById('num1').value;
      var num2 = document.getElementById('num2').value;
      if (num1 == '' || num2 == '') {
        document.getElementById('status').innerHTML = 
        'Enter input numbers to continue';
      }
      else {
        var result = nativeObject.computeSubstraction
        (num1, num2);
        document.getElementById('status').innerHTML = '';
        document.getElementById('subResult').innerHTML = 
        result;
      }
    }
    
    function MultiplicationButton_Click() {
      var num1 = document.getElementById('num1').value;
      var num2 = document.getElementById('num2').value;
      if (num1 == '' || num2 == '') {
        document.getElementById('status').innerHTML = 
        'Enter input numbers to continue';
      }
      else {
        var result = nativeObject.computeMultiplication
        (num1, num2);
        document.getElementById('status').innerHTML = '';
        document.getElementById('mulResult').innerHTML = 
        result;
      }
    }
  9. Now press the F5 key to run the application.

  10. Enter the two numbers and click on the Addition of Two Numbers button or on any of the shown buttons to display the computation.

How it works...

The Class1.h and Class1.cpp files have a public ref class. It's an Activatable class that JavaScript can create by using a new expression. JavaScript activates the C++ class Class1 and then calls its methods and the returned values are populated to the HTML Div.

There's more...

While debugging a JavaScript project that has a reference to a WinRT component DLL, the debugger is set to enable either stepping through the script or through the component native code. To change this setting, right-click on the JavaScript project and go to Properties | Debugging | Debugger Type.

If a C++ Windows Runtime component project is removed from a solution, the corresponding project reference from the JavaScript project must also be removed manually.

 

Porting a desktop app to a Windows Store app (Become an expert)


In this recipe, you will learn how to convert existing code to a Windows Store app for Windows 8. You can't simply convert the code line-by-line; you should redesign the user interface for the Windows Store app. When you are migrating your desktop apps to Windows Store apps, the first thing is to evaluate the reusable code in your application. Not all of the code can be re-used, so you can separate the application code into the UI logic and business logic code. For Windows Store apps, the Model View View-Model (MVVM) design pattern is recommended to isolate the view and the model.

Getting ready

Please refer to the PortingDesktopToWinStore project for the full working code to create a WinRT Component and consume it in Javascript.

How to do it...

In this recipe, you will learn to make use of traditional Win32 DLLs into Windows Store apps. If you have a Microsoft Foundation Class (MFC) application, you need to decouple the UI from business logic, create a Win32 DLL or Windows Runtime DLL, create a Windows Store app user interface, and use the DLL as shown in this example.

The first thing we will do is create a Win32 DLL that will expose a function to find the largest number in a range of numbers, by using the following steps:

  1. Start Visual Studio 2012. Create a new Win32 project called Win32MaxNumber. Then go to Application Settings. Check DLL and Empy Project. Click on Finish.

  2. Go to Solution Explorer. Right-click on Header Files. Add a new header file. Create a new file called MaxNumber.h. Add the following code into that file:

    // MaxNumber.h
    #include <vector>
    using namespace std;
    
    namespace Win32MaxNumber
    {
      class MaxNumber
      {
      public:
        static __declspec(dllexport) 
        double FindMaxNumber(string numbers);
        static __declspec(dllexport) vector<double> 
        split(const string &text, char sep) ;
      };
    }
  3. Go to Solution Explorer. Right-click on Source Files. Add a new source file. Create a new file called MaxNumber.cpp. Add the following code into that file:

    // MaxNumber.cpp
    
    #include "MaxNumber.h"
    
    #include <iostream>
    #include <cmath>
    
    namespace Win32MaxNumber
    {
      double MaxNumber::FindMaxNumber(string numbers)
      {
        vector<double> v = split(numbers, ',');
        /*vector<double>::iterator result;
        result = max(begin(v), end(v));		
        int pos = std::distance(v.begin(), result);
        return v[pos];*/
        double max = v.front();
        for (unsigned int i = 0; i < v.size(); i++)
        {
          if (v[i] > max)
          max = v[i];
        }
    
        return max;
      }
    
      vector<double> MaxNumber::split(const string &text, 
      char sep) 
      {
        int start = 0, end = 0;
        vector<double> tokens;
        while ((end = text.find(sep, start)) != string::npos) {	  
          tokens.push_back(std::atof(text.substr
          (start, end - start).c_str()));
          start = end + 1;
        }
        tokens.push_back(std::atof(text.substr
        (start).c_str()));
        return tokens;
      }
    }
  4. Save the project and build it.

  5. This will create Win32MaxNumber.dll, which will be consumed in the Windows Store app and will call FindMaxNumber and build the UI using XAML to input the range of numbers.

  6. Now right-click on the solution and click on Add New Project. Choose VC++ from the left pane and then select Windows Store App; name the project as PortingDesktopToWinStore.

  7. Now copy Win32MaxNumber.dll, Win32MaxNumber.lib, and MaxNumber.h into the working directory of the PortingDesktopToWinStore project and include these files into the project by right-clicking on the files and selecting Include In Project.

  8. Right-click on the PortingDesktopToWinStore project. Choose Properties. Then go to Configuration Properties | Linker | Input and add the .lib file as a dependency as shown in the following screenshot:

  9. Right-click on Win32MaxNumber.dll in Solution Explorer and go to Properties | Content | True.

  10. Add the following code in the Main.xaml file:

    <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
    
      <Grid.ColumnDefinitions>
        <ColumnDefinition Width="124"/>
        <ColumnDefinition/>
      </Grid.ColumnDefinitions>
      <Grid.RowDefinitions>
        <RowDefinition Height="120"/>
        <RowDefinition Height="Auto" MinHeight="145"/>
        <RowDefinition/>
      </Grid.RowDefinitions>
      <TextBlock HorizontalAlignment="Left" TextWrapping="Wrap" VerticalAlignment="Top" Grid.Column="1" Margin="10,41,0,0" Height="38" Width="316" FontSize="32" Text="Find Maximum Number"/>
      <TextBlock HorizontalAlignment="Left" TextWrapping="Wrap" VerticalAlignment="Top" Grid.Column="1" Margin="10,111,0,0" Height="38" Width="270" FontSize="16" Text="Enter Number Separated by comma" Grid.RowSpan="2"/>
      <TextBox x:Name="InputTextBox" Grid.Column="1" HorizontalAlignment="Left" Height="24" Margin="285,111,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="295" Grid.RowSpan="2"/>
      <Button x:Name="FindMaxNum" Content="Find Max Number" HorizontalAlignment="Left" VerticalAlignment="Top" Grid.Column="1" Margin="10,102,0,0" FontSize="16" Grid.Row="1" Height="39" Width="204" Click="FindMaxNum_Clicked"/>
      <TextBlock Grid.Column="1" HorizontalAlignment="Left" Height="24" Margin="249,110,0,0" Grid.Row="1" TextWrapping="Wrap" Text="Max Number" FontSize="16" VerticalAlignment="Top" Width="119"/>
      <TextBlock x:Name="MaxResultBlock" TextWrapping="Wrap" Text="" Grid.Column="1" Margin="363,110,615,487" Grid.Row="1" Foreground="#FF2118E8" FontSize="16" LineStackingStrategy="BlockLineHeight" Grid.RowSpan="2"/>
    
    </Grid>
  11. Add the FindMaxNum_Clicked event for the button FindMaxNum.

  12. Add the following declarations in the Main.xaml.h file after the #include "MainPage.g.h" line:

    #include "MaxNumber.h"
    
    using namespace std;
    using namespace Win32MaxNumber;
  13. In the private section declaration, add the following line:

    unique_ptr<MaxNumber> maxNumber_;
  14. Open the file Main.xaml.cpp and add the following code for the FindMaxNum _ Clicked event.

    void MainPage::FindMaxNum_Clicked(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
    {
      String^ userText = InputTextBox->Text;
      if (userText != nullptr && !userText->IsEmpty())
      {
        string numbers( userText->Begin(), userText->End() );
        double result = maxNumber_->FindMaxNumber(numbers);
        MaxResultBlock->Text = result.ToString();
      }
    }
  15. Press the F5 key to run the application.

  16. In the Input box, enter the number range separated by a comma and then click on the Find Max Number button. The result is displayed in the Max Number text block.

How it works...

In the preceding example we used Win32 DLL, which is built in Visual Studio 2012. Win32 DLLs can be loaded by Windows Store apps in static or dynamic ways. In general, your desktop application's business logic code is wrapped into Win32, COM, or .NET libraries. The corresponding mapping in the Windows Store app is done using Windows Runtime components. We have different ways to re-use our code. You can load your existing libraries in your Windows Runtime components, rewrite your logic in Windows Runtime components, or directly load your Win32 DLLs in the Windows Store app as shown in this recipe.

 

Packaging and deploying your app to the Windows Store (Become an expert)


Millions of customers can find, try, and buy high-quality, certified apps from anywhere in the world using the Windows Store. You can distribute, update, and get paid for the apps that you develop, through the Windows Store.

The Windows Store allows your apps to be searched, ranked by users, and browsed based on categories and languages, thus promoting your apps. It distributes free as well as paid apps.

It provides you a dashboard to view reports on downloads, revenues, aggregated usages, in-app transactions, customer ratings, market trends, and crash and hang data.

In this recipe, you will learn the steps to be followed to package and deploy your app to the millions of customers out there.

Getting ready

Publishing your apps to the Windows Store requires you to do the following:

  • Satisfy Microsoft app requirements and the developer agreement

  • Have a Windows Store developer account

  • Test and validate your app using the Windows App Certification Kit

How to do it...

The following is the walkthrough to help you through the process of getting your app published to the Windows Store:

  1. Get your Microsoft Store account.

  2. Once you have set up an account, go to the dashboard.

  3. Clicking on Submit an app displays the following page.

When submitting an app, you need to fill the following 8 sections:

  • App name: This is to reserve your app's name; the name will be kept reserved for 12 months.

  • Selling details:

    • Here you need to set the price and trial period for your apps.

    • Now select the release date on the same page. If your app is to be published soon, choose the first option.

    • Now choose the category and subcategory for your app.

  • Advanced features: Only if your application supports in-app purchases do you need to fill up this section. In-app purchasing is a great way of making money; for example, your app is free but to play advanced games, users may be required to buy some points.

  • Age rating: In this section, you can choose the audience age certificate.

  • Cryptography: If your app requires cryptography or encryption, you must read up on the regulations to see if your app needs an Export Commodity Classification Number (ECCN).

  • Packages: Perform the following steps to create an app package for the Windows Store:

    1. Right-click on Solution Explorer. Go to Project | Store | Create App Packages.

    2. The Create App Packages wizard appears. Enter your Microsoft account username and password and then click on the Sign In button.

    3. Select your app's name, which was kept reserved in the App name section, and then click on the Next button.

    4. Enter the output location and version, and then click on Create.

    5. When the Package Creation Completed message appears, validate your package using the Windows App Certification Kit.

    6. Click on the Launch Windows App Certification Kit button.

    7. On the Windows App Certification Kit wizard, click on Next.

    8. The Windows App Certification Kit lists all the Windows Store apps that you have deployed on your computer.

    9. The Windows App Certification Kit begins testing the app.

    10. At the prompt after the test, enter the path to the folder where you want to save the test report.

    11. The Windows App Certification Kit creates an HTML along with an XML report and saves it in this folder.

    12. Open the report file and review the results of the test.

  • Description: Here you need to describe what your app is all about and this description will be visible to users when they look at your app in the Windows Store.

  • Notes to testers: Here you need to add notes to share with the people who are testing your app for certification.

How it works...

Once your app is submitted, it takes up to two weeks to get certified; the progress can be tracked on the main dashboard.

Millions of people can now browse for your app and download and install it on different devices.

About the Author

  • Taruna Verma

    Taruna Verma has performed many challenging roles in various positions, gathering a healthy mix of strong technological orientation to solve business problems, over the past ten and half years or so. Taruna owns and runs a company called Tarav Technologies Private Limited, based out of Bangalore, India, to provide Microsoft-based development and IT training. Prior to starting her own consulting services, she worked in Siemens Medical Systems, Microsoft R&D, SAP Labs, and Yokogawa Engineering, Singapore. She has many satisfied customers, including Fortune 500 companies, startup companies, and government organizations. Besides her love for different technologies, Taruna has also conducted numerous training sessions in different software firms globally. Taruna enjoys writing stories, poems, blogging, travelling, and watching movies. Her professional profile is available at http://www.linkedin.com/in/tarunaverma.

    Browse publications by this author

Latest Reviews

(1 reviews total)
Just for reference. Not really of interest at present.
Instant Windows 8 C++ Application Development How-to
Unlock this book and the full library FREE for 7 days
Start now