Chapter 2. App packaging and deployment

In Chapter 1 you learned that one of the design goals for Windows Store apps was that Windows should be able to cleanly install and uninstall the app so that users have confidence that an app will not irreparably affect their system. This means that everything your Windows Store app needs to run successfully must be combined together so that the system knows the complete footprint of your app. The resulting file is called an app package, and it contains binaries such as your executable, libraries, and Windows Runtime (WinRT) components. It also contains resource files your app uses such as images and media files. You use Microsoft Visual Studio to build your app and create your app’s package file. This package file then can be uploaded to the Windows Store, enabling users to install it on their PCs, or you can manually distribute the package, enabling users to manually install (sideload) it on their PCs. Of course, Windows only installs packages that come from trusted sources, and it will make sure that the package’s contents have not changed in transit.

In this chapter, I show how to build a package and what the package contains. You’ll also see the different ways to deploy a package to users’ PCs. I’ll then go into more details on package installation, including staging and registration. Finally, I’ll finish with some specifics regarding the use of Visual Studio and debugging. This is a very important chapter in helping you understand how to work with Windows Store apps. The concepts presented in this chapter are very useful and will help you understand the concepts presented throughout later chapters in this book.

A Windows Store app’s project files

In this section, we look at the various files that make up a Windows Store app’s package, with an emphasis on the manifest file. I’ll also show how Visual Studio builds all the files and places them into a package file.

The first time you create a Windows Store app project in Visual Studio, Visual Studio prompts you with a dialog box telling you that you need to get a developer license, as you see in Figure 2-1. Developer licenses allows apps to run that have not been downloaded from the Windows Store. This is certainly useful when developing, testing, and debugging an app. Developer licenses expire every 30 days (90 days if you have registered an account with the Windows Store), but they are free to acquire. After your developer license expires, Visual Studio automatically prompts you to renew it. Windows provides PowerShell commands (shown in Table 2-1) to manage a PC’s developer license.

Visual Studio’s Developer License dialog box prompting the user to install the license.

Figure 2-1. Visual Studio’s Developer License dialog box prompting the user to install the license.

Table 2-1. PowerShell commands to manage a PC’s developer license

PowerShell command

Description

Show-WindowsDeveloperLicenseRegistration

Renews the PC’s developer license

Unregister-WindowsDeveloperLicense

Unregisters the developer license from the PC

Get-WindowsDeveloperLicense

Checks the validity and expiration date of the developer license on the PC

A Windows Store app project consists of many folders and files:

  • In the Properties folder, you’ll find the AssemblyInfo.cs file. This is the standard AssemblyInfo.cs file with assembly attributes for your project, such as AssemblyTitle, AssembyDescription, AssemblyVersion, and so on. This file is used in .NET assemblies and is not specific to Windows Store apps. For more information about them, see CLR via C#, Fourth Edition (Microsoft Press, 2012) by Jeffrey Richter.

  • In the References folder, you’ll find two entries. The first, “.NET for Windows Store apps,” exposes the subset of the .NET Framework Class Library you can call from Windows Store apps (as discussed in Chapter 1). The second entry, “Windows,” exposes the WinRT APIs provided by the Windows operating system that are callable by Windows Store apps.

  • The Assets folder contains nonexecutable (resource) files, such as images and media files. These files are packaged and deployed with your app. By default, Visual Studio places image files in this folder that are for your app’s store logo, splash screen, small app logo, and primary Start screen tile.

  • Package.appxmanifest is an XML file that describes your Windows Store app. We’ll explore the manifest in this chapter’s next section and refer back to it frequently throughout this book. If you open the file in Visual Studio, you can see that the IDE provides a user-friendly editor for this manifest file. This user interface is called the manifest designer.

  • A {project}_TemporaryKey.pfx file that contains a Software Publishing Certificate (SPC). Every Windows Store app must be signed with a certificate. Every time you create a new project, Visual Studio generates an untrusted, self-signed, code-signing certificate that expires in one year. Your app package file is signed with this certificate. Of course, Windows will not execute the contents of the package if the certificate is untrusted. To get your package to execute, the certificate must be added to the PC’s trusted certificate store or the package will have to be signed with another certificate that is trusted. I’ll talk about the certificates more in this chapter’s Deploying a Windows Store package section. When you’re debugging an app, a certificate is not required because you are not creating and deploying a package.

  • The App.xaml and App.xaml.cs files contain XAML resources and the code behind for your app. The contents of this file and how your app are activated is discussed in Chapter 3.

  • Other XxxPage.xaml and XxxPage.xaml.cs files contain the XAML markup and code behind for your app’s other pages. Because this book does not go into designing and building user interfaces, these other files are not discussed, although Chapter 3 does explore page navigation.

The app’s package manifest file

The Package.appxmanifest file is referred to as the app’s package manifest file, and you use it to describe the following:

  • Your package’s identity so that the Windows Store and Windows itself can uniquely identify your package. It is critically important to understand that Windows installs packages, not apps.

  • The apps that ship inside the package and some UI-related features of each app. A single app package can contain multiple apps. However, Microsoft’s user-experience team discovered a series of problems with this approach. For example, if a user uninstalled one of the package’s apps, how could the user re-install it later? To simplify the user experience, the Windows Store has a policy that all packages must contain a single app. For this reason, Visual Studio’s manifest designer supports only single app packages.[15] In addition, due to this simplification, the terms package and app are sometimes (unfortunately) used interchangeably.[16] For example, a more accurate term for application data is package data and a more accurate term for app container is package container because the data and the container are really owned by the package, which might consist of multiple apps. This is especially important to understand when working with background tasks because an app can have multiple background task processes all sharing the same data and container.

  • The visual assets for your app. This includes the foreground text color and background color that make up your app’s theme as well as the various logos (images) for your app’s splash screen and static tiles.

  • The device resources (capabilities) that each app in the package wants access to.

  • The various ways the system can activate (open) each app in the package. In the manifest designer, these are called declarations, but in the XML schema, these are called extensions. Sometimes activations, declarations, and extensions are also referred to as contracts.

  • Which pages in the web context have access to the system’s geolocation devices and access to the clipboard. This is used for apps written in JavaScript, not for apps written in C#.

When you open the Package.appxmanifest file in Visual Studio, the manifest designer appears. The manifest designer exposes a graphical user interface for changing common manifest settings. For more advanced settings (like the Document Library capability or to declare support for the appointments or contacts activations), you must manually edit the XML file. The schema for the manifest’s XML file can be found at http://msdn.microsoft.com/en-us/library/windows/apps/br211473.aspx.

The next three sections detail a package’s identity as well as an app’s capabilities and declarations. The manifest’s Application UI information is discussed in other chapters.

Package identity

Figure 2-2 shows the manifest designer’s Packaging tab.

Visual Studio showing the manifest designer’s Packaging tab.

Figure 2-2. Visual Studio showing the manifest designer’s Packaging tab.

You use this tab to establish your package’s identity. Because these properties identify your package in the Windows Store and when it is installed, some of them are not completely under your control.

  • Package Name. identifies the name of your package. When you create a new project in Visual Studio, Visual Studio creates a GUID and uses it for your package’s name. This should be changed to a more user-friendly name. Frequently, package names use a scheme such as “CompanyName.AppName”—for example: “Microsoft.Bing.”

    If you intend to distribute your package via the Windows Store, you should go to the Windows Store dashboard, reserve a name for your package, and then use Visual Studio’s “Associate App with the Store” wizard to associate your package with your reserved package name. When you do this, Visual Studio automatically updates these manifest values: Package Name, Package Display Name, Publisher, Publisher Display Name, Version, and Application Display Name (shown on the designer’s Application tab). If you do not intend to deploy your app via the Windows Store, you can change these manifest values manually to whatever you like.

  • Package Display Nameis the friendly name that users see in the Windows Store. The Windows Store requires that every package have a unique package display name. This was done to prevent a malicious person from producing a “Finance” app that has the same look and feel as a respectable company’s “Finance” app, thereby spoofing the user to enter her personal financial data into the malicious app, where it can be stolen and abused.

  • Version. identifies the major, minor, build, and revision numbers you want to associate with your app. We’ll talk about this more when we discuss creating an app’s package.

  • Publisher. is the subject of the certificate that Visual Studio uses when signing the package file. This changes when the certificate changes. When you create a new project in Visual Studio, Visual Studio creates a certificate whose subject is the name of the user logging in to Windows. However, you can always generate a new certificate on your local machine, use a certificate obtained by your company, or obtain a certificate from the Windows Store by associating your app with the Windows Store.

  • Publisher Display Name. is the friendly name of the publisher. When you create a new project in Visual Studio, Visual Studio sets the Publisher Display Name to the name of the user logging in to Windows. When you associate an app with the Windows Store, the Publisher Display Name is set to the value you entered for the Publisher Name field in the Windows Store dashboard.

  • Package Family Name. is a computed read-only value that is generated by concatenating two values: the Package Name and the Publisher ID. The Publisher ID is produced by creating a hash value for the Publisher string and then base 32–encoding this hash value. The result is always a 13-character string that uniquely identifies the publisher (statistically). A package family name string uniquely identifies a package from a specific publisher. Here is an example for one of my apps, called Clips & Pieces: “JeffreyRichter.ClipsPieces_ape9s8gs6w87m”.

  • Generate App Bundle. has nothing to do with your package’s identity. It just tells Visual Studio how to generate a package file or files. I explain what an app bundle package is in the Creating a bundle package file section.

In addition to the package family name, there is also a string referred to as the package full name. The package full name is a concatenation of the package name, its version, its CPU architecture (x86, x64, ARM, or Neutral), a Resource ID (usually an empty string, “”), and the Publisher ID. Here is an example of my app’s package full name: “JeffreyRichter.ClipsPieces_1.0.0.0_neutral__ape9s8gs6w87m”. Most packages do not specify a Resource ID (in fact, Windows does not interpret this value), which is why my app’s package full name doesn’t show any resource ID information between the CPU architecture and the Publisher ID. There are just two underscores right next to each other.

When your Windows Store app is running, it can obtain information about its package by querying Windows.ApplicationModel.Package’s static Current property. This property returns a reference to a Package object that looks like this:

public sealed class Package {
   public static Package Current { get; }  // Gets calling app's package
   public PackageId Id { get; }  // See the PackageId class below
   // Members returning package attributes:
   public String DisplayName          { get; }
   public String PublisherDisplayName { get; }
   public String Description          { get; }
   public Uri    Logo                 { get; }
   // Package's files under %ProgramFiles%WindowsApps
   public StorageFolder InstalledLocation { get; }
   // Returns framework packages this package requires to run
   public IReadOnlyList<Package> Dependencies { get; }
   // Properties indicating the type of package
   // If all return false, this is an .appx package containing 1 or more apps
   public Boolean IsFramework       { get; }
   public Boolean IsBundle          { get; }
   public Boolean IsResourcePackage { get; }
   // True when Visual Studio launches the app
   // If true, you can enable debugging/testing features in your app
   public Boolean IsDevelopmentMode { get; } // True if registered; not staged
}

The Id property returns a PackageId object that looks like this:

public sealed class PackageId {
   public String Name        { get; }  // Package name
   public String Publisher   { get; }  // Publisher name
   public String PublisherId { get; }  // Base-32 hash of Publisher
   public String FamilyName  { get; }  // Name_PublisherID
   public PackageVersion        Version      { get; } // Ex: "1.2.3.4"
   public ProcessorArchitecture Architecture { get; } // Neutral, x86, x64, ARM
   public String                ResourceId   { get; } // Usually ""
   // Name_Version_Architecture_ResourceId_PublisherID:
   public String                FullName     { get; }
}

Capabilities

When developing an app, you must indicate which secured system resources (or device capabilities) your app wants access to in the package manifest. Figure 2-3 shows the manifest designer’s Capabilities tab. Some capabilities are so rarely used (or discouraged) that they do not appear in the manifest designer; to add these capabilities, you must manually edit the manifest XML file. Table 2-2 lists all the capabilities.

Visual Studio showing the manifest designer’s Capabilities tab.

Figure 2-3. Visual Studio showing the manifest designer’s Capabilities tab.

Table 2-2. Capabilities

Capability

Description

Additional confirmation

Documents Library1[a]

Provides programmatic access to the user’s Documents library. You’ll need to declare a file type association as well.

Music Library

Provides programmatic access to the user’s Music library folders

Pictures Library

Provides programmatic access to the user’s Pictures library

Videos Library

Provides programmatic access to the user’s Videos library

Removable Storage

Provides programmatic access to the removable storage, such as USB drives

Internet (Client)

Provides outbound Internet access (on by default in the templates)

Internet (Client & Server)

Provides inbound as well as outbound Internet access. Superset of Internet (Client)

Private Networks (Client & Server)

Provides inbound and outbound connectivity over a home or work network

Enterprise Authentication[b]

Enables your app to use your credentials to authenticate on the network

Shared User Certificates[c]

Provides access to certificates, for example, on a smartcard

Proximity

Provides access to the NFC sensor for bootstrapping connections with other devices and electronic wallet scenarios

Location

The machine’s geo-location provided by a GPS or derived from network info

Microphone

Provides access to the machine’s microphone audio stream

Webcam

Provides access to the machine’s camera audio and video stream

[a] Three capabilities are referred to as special use capabilities and should be avoided. Enabling any of these capabilities will fail Windows Store certification if the package is submitted by an individual. Only companies (whose identity has been verified) can submit packages enabling these capabilities. For more information, see http://msdn.microsoft.com/en-us/library/windows/apps/hh464936.aspx.

[b] Three capabilities are referred to as special use capabilities and should be avoided. Enabling any of these capabilities will fail Windows Store certification if the package is submitted by an individual. Only companies (whose identity has been verified) can submit packages enabling these capabilities. For more information, see http://msdn.microsoft.com/en-us/library/windows/apps/hh464936.aspx.

[c] Three capabilities are referred to as special use capabilities and should be avoided. Enabling any of these capabilities will fail Windows Store certification if the package is submitted by an individual. Only companies (whose identity has been verified) can submit packages enabling these capabilities. For more information, see http://msdn.microsoft.com/en-us/library/windows/apps/hh464936.aspx.

When the user views a package in the Windows Store, the user is shown the device capabilities that the package has enabled under the “This app has permissions to use” section. The user implicitly grants the package these capabilities by installing the package. The fewer capabilities your package requires, the more users can trust it, and this improves your app’s market penetration. Note, if the developer adds capabilities to a package in the future and uploads a new version of the package to the Windows Store, the new version of the package gets installed on all users’ PCs automatically; the user is not informed that the new version can access additional resources. The user can always verify what capabilities an installed package has by running that package’s app and then looking at its Settings charm > Permissions pane.

Some capabilities require additional approval from the user. The first time an app tries to access the user’s location, microphone, or webcam, the system prompts the user for additional confirmation. To pass Windows Store certification requirements, your app must function reasonably well if the user fails to grant your app access to these resources. In addition, a user can always revoke access to any of these resources at any time by opening the Settings charm > Permissions pane.

App (not package) declarations (extensions/contracts)

When developing an app, you must indicate the various ways the system can activate your app in the manifest. Figure 2-4 shows the manifest designer’s Declarations tab. Some declarations are so rarely used that they do not appear in the manifest designer; to add these declarations, you must manually edit the XML file. Also, note that some declarations can be specified multiple times for a single app. For example, a single app can support multiple file type associations, protocols, background tasks, AutoPlay contents, and AutoPlay devices. Table 2-3 lists all the declarations.

Visual Studio showing the manifest designer’s Declarations tab.

Figure 2-4. Visual Studio showing the manifest designer’s Declarations tab.

Table 2-3. App declarations (extensions/contracts)

Declaration

Allows the system to activate your app when…

File Type Associations

The user or another app launches a file of a type your app supports (such as “.txt”).

See the Windows.System.Launcher class.

Protocol

The user or another app launches a URI protocol your app supports (such as mailto:).

See the Windows.System.Launcher class.

Background Tasks

A timer or system event triggers.

See the Windows.ApplicationModel.Background.BackgroundTaskBuilder class.

Share Target

The user wants to share some data from another app to your app.

See the Windows.ApplicationModel.DataTransfer.DataTransferManager class.

File Open Picker

The user wants to open a file from your app via the file open picker.

See the Windows.Storage.Pickers.FileOpenPicker class.

File Save Picker

The user wants to save a file to your app via the file save picker.

See the Windows.Storage.Pickers.FileSavePicker class.

Cached File Updater

Another app wants to read/write to a file your app returned via a picker.

See the Windows.Storage.Provider.CachedFileUpdater class.

Search

Provides integration with the Search charm.

See the Windows.ApplicationModel.Search.SearchPane class.

Contact Picker

Enables your app to provide contact data.

See the Windows.ApplicationModel.Contacts.ContactPicker class.

AutoPlay Content

User inserts a removable storage device into the PC.

See http://msdn.microsoft.com/en-us/library/windows/apps/hh452741.aspx.

AutoPlay Device[a]

User attaches a hardware device to the PC.

See http://msdn.microsoft.com/en-us/library/windows/apps/hh452741.aspx.

Camera Settings[b]

Enables your app to provide a custom UI for a camera.

See http://msdn.microsoft.com/library/windows/hardware/hh454870.

Print Task Settings[c]

Enables your app to provide a custom UI for its printer.

See http://msdn.microsoft.com/en-us/library/windows/hardware/br259129.

Account Picture Provider

User wants to use your app to change his account picture.

See the Windows.System.UserProfile.UserInformation class.

Lock screen call

The user is using your app to answer a call while on the lock screen. See the Toast XML schema’s command element.

Contact

The user is trying to message, mail, call, video call, or map a person using your app.

See Windows.ApplicationModel.Contacts.ContactManager.

Alarm

The system is within 1 second of an alarm coming due.

See the Windows.ApplicationModel.Background.AlarmApplicationManager class.

Appointment provider

The user is trying to modify a calendar appointment or view a time frame using your app.

See Windows.ApplicationModel.Appointments.AppointmentManager.

[a] These declarations are used by companion apps that accompany devices, such as cameras and printers.

[b] These declarations are used by companion apps that accompany devices, such as cameras and printers.

[c] These declarations are used by companion apps that accompany devices, such as cameras and printers.

Note

The terms app declaration, app extension, app activation, and contract all relate to the exact same thing. That is, in your package, you must declare an app extension, allowing the system to activate your app. We say that your app implements a contract when it responds to an activation.

In addition to the app declarations shown in Table 2-3, the package itself can have some declarations. Because package declarations are associated with a package, they have nothing to do with app activation. There are five package declarations: Certificates (the most useful), GameExplorer, InProcessServer, OutOfProcessServer, and ProxyStub. This declaration allows you to embed one or more certificates in your package, and this certificate will be part of your package’s private certificate store, thereby making it available to the app in the package. The certificate is typically used to secure network communication between a package’s app and an Internet service. (See Chapter 7.)

Building a Windows Store app package

When you’re developing and debugging your app, Visual Studio registers and runs your app from the project’s build directories (discussed more in this chapter’s Debugging Windows Store apps section). But, when you’re ready to distribute an app, you must create a package file. From within Visual Studio, select Project Menu > Store > Create App Packages (or, with Visual Studio Express, select Store Menu > Create App Packages). Visual Studio presents you with the option to create either a package you can manually distribute or a package you can upload to the Windows Store. When you create a package to upload to the Windows Store, Visual Studio prompts you to associate your package with an app name that you must have previously reserved for yourself via the Windows Store dashboard. We’ll look into the details of creating an app for the Windows Store in Chapter 11.

The next step in the Create App Packages wizard (shown in Figure 2-5) is to specify your app’s package version, supported CPU architecture or architectures, and solution configuration such as Debug or Release. I’ll talk about the Generate App Bundle setting in the Creating a bundle package file section.

For the CPU architecture, you can choose between Neutral, x86, x64, and ARM. C# Windows Store app projects default to Neutral (Any CPU) and packages built with this setting run on all three CPU architectures. However, your app can use other Windows Store components built in .NET or C++. If your app uses a component built for a specific CPU architecture (like Bing Maps), you must build one or more CPU-specific packages. Apps built for x86 will run on both x86 and x64 machines. The Windows Store uses the architecture information to filter out apps for the user’s PC. Hence, if your app supports only x86, users with Windows RT machines (ARM processor machines) will not see your app when they are browsing in the Windows Store app.

Visual Studio’s Create App Packages wizard.

Figure 2-5. Visual Studio’s Create App Packages wizard.

The Create App Packages wizard populates the version from the manifest file; changing the numbers updates the manifest file. If you select multiple architectures in the wizard, the build process creates multiple app package files. The check box asking for public symbol inclusion tells the wizard to create an additional file per chosen CPU architecture. These files contain public symbol information that allows Microsoft to provide you with better diagnostics in the Windows Store dashboard if your app crashes. (For more information, see Chapter 11.)

When you click the wizard’s Create button, the build process starts as described by Figure 2-6.

Process of building an app package file.

Figure 2-6. Process of building an app package file.

Here’s what happens:

  1. An MSBuild task generates source code files from the XAML markup, such as App.g.i.cs and MainPage.g.i.cs. This step is not shown in Figure 2-6.

  2. The C# compiler (CSC.exe) compiles your source code files as well as the dynamically generated source code files, together producing a managed executable assembly (exe file). Producing a Windows Store app requires the /target:appcontainerexe compiler switch. By default, your executable will run on all CPU architectures, because Visual Studio adds the /platform:anycpu32bitpreferred compiler switch. Use the /platform:anycpu switch to use more address space when running on an x64 system.

  3. Other files your app needs, such as referenced assembly files and other resource assets (such as images, music, videos), are also copied to the same directory as your .exe file. Your XAML files are compiled to a binary form and placed in this directory as files with an .xbf extension.

  4. For string resources and other asset files, a utility called MakePRI.exe creates a Package Resource Index (.pri) file. (See http://msdn.microsoft.com/en-us/library/windows/apps/jj552947.aspx for details.) Windows Store apps use this .pri file at runtime to load resources efficiently. The file contains your app’s strings and an indexed set of file paths to other app resources. There is one .pri file for all the languages your app supports. The .pri file is also written to the same directory.

  5. The final manifest file (AppxManifest.xml) is almost identical to your project’s Package.appxmanifest file discussed earlier in this chapter. However, MSBuild does tweak some of the values inside the file for you.

  6. MSBuild then spawns MakeAppx.exe to create an unsigned .appx package file consisting of all the produced files. An app package file is simply a ZIP file with an .appx file extension. It cannot have more than 100,000 files in it, and it can’t be larger than 8 GB in size.

  7. As a final step, MSBuild invokes SignTool.exe to sign the .appx file using the certificate that is part of your Visual Studio project.

You now have a single .appx package file containing your app and everything it needs in order to execute once this package gets installed on a user’s PC. In the next section, we’ll look at the contents of this .appx package file.

Contents of an .appx package file

If you look in a directory produced by the Create App Packages wizard, you’ll see files similar to those listed in Table 2-4.

Table 2-4. Files created by the Create App Packages wizard for a single CPU architecture

File or folder name

Description

PackageSample_1.0.0.0_AnyCPU_Debug.appx

Signed package (ZIP) file containing all assemblies, resources, and so on.

PackageSample_1.0.0.0_AnyCPU_Debug.appxsym

ZIP file containing any symbols (.pdb files) for the assemblies embedded inside the .appx file. This file is produced if you select the Include Public Symbol Files check box (shown in Figure 2-5), and it allows you to get richer debugging information if your app experiences an unhandled exception when running on a user’s PC.

PackageSample_1.0.0.0_AnyCPU_Debug.cer

Certificate file containing the public key corresponding to the private key used to sign the .appx file.

Add-AppDevPackage.ps1

PowerShell script you can use to install the package on a PC.

Add-AppDevPackage.resources

Subdirectory with localized strings used internally by the .ps1 file.

The .appx and .appxsym files are simply ZIP files. In fact, you can change the extension of these files to .zip to examine their contents. Table 2-5 shows the contents of an .appx file. Here, you can see the files resemble your project’s folder structure, containing directories such as Assets and Common.

Table 2-5. Contents of an .appx file

File/directory

Contents

[Content_Types].xml

File listing the file types used in this package. See the Office Open XML file specification for more information.

AppxMetadata

Folder containing a CodeIntegrity.cat file used to validate the integrity of the .appx file’s contents.

AppxBlockMap.xml

Contains hash values for blocks within the .appx file’s files.

AppxManifest.xml

Generated XML manifest file.

AppxSignature.p7x

Contains the digital signature produced when signing the .appx file with your project’s certificate (.pfx file).

PackageSample.exe

The app’s executable.

App.xbf

Markup for the app.

MainPage.xbf

Markup for the app’s main page.

Common

Folder containing common files, such as StandardStyles.xaml.

Assets

Folder containing the resources (images, and so on).

resources.pri

Package resource index file.

You can easily open any of the files in this .appx ZIP file because Visual Studio does not encrypt the file or any of its contents. If you open AppxBlockMap.xml, you’ll see a list of files along with a hash value and size for each 64-KB compressed block of the file. The MakeAppx.exe utility created this AppxBlockMap.xml file. Windows uses the AppxBlockMap.xml file to verify the integrity of the package’s files, ensuring that no modifications have been made to any of the file’s contents after the .appx file was created.

Another cool feature provided by the AppxBlockMap.xml file is differential download. When creating a new version of your app, it is common to keep most of your existing asset files while modifying just a few of them or including some new asset files. When a user installs a new version of your package, Windows uses the AppBlockMap.xml file to see which files have changed and only downloads the portions (blocks) within files that have been updated. This greatly improves the speed of installing a newer version of an application and also decreases network usage, resulting in cheaper network charges for the user.

Furthermore, if multiple packages ship the same files (regardless of publisher), the system knows that the files are already installed (based on the hash values) and just creates NTFS hard links to the files. This greatly reduces download time and prevents the wasting of disk space by having the same file installed multiple times. For example, if multiple packages ship the same SQLite or Bing Maps files, the files will be downloaded just once and reside just once on the user’s PC. For this reason, you should try to use the same files across multiple packages; avoid making special one-off builds that alter just a few bits here and there.

In Table 2-5, you see the AppxManifest.xml file that Visual Studio generated from the original Package.appxmanifest file. Most of the content of these two files is identical except for a few replacements and additions. For example, the <Resources> section now contains the languages your app supports. In addition, references to extension SDK packages get added to the <Extensions> node.

In addition to creating the files in Table 2-4, Visual Studio’s Create App Packages wizard also generates an .appxupload file. This file is simply a ZIP file containing the .appx and .appxsym files. You can upload an .appxupload file to the Windows Store via the Windows Store dashboard.

Creating a bundle package file

The .appx package file described in the previous section is sometimes referred to as a fat package because it can become huge. It becomes huge if the package includes resources for many languages, many screen resolutions, or if it contains texture maps for various versions of DirectX. But when a user installs a package, that user may only ever need one set of language resources, one set of images for their monitor’s resolution, and one set of texture maps for their video card. Installing a fat package installs all of its files whether the user needs them or not. Depending on the package, this can be a huge waste of bandwidth and a huge waste of disk space.

You can improve this situation for your users by creating a bundle package file. A bundle package file is a different kind of package file. Like an .appx package file, a bundle package file also has an identity composed of a package name, version, and publisher ID; the resource ID is always tilde (~), and the CPU architecture is always “neutral.”

In Figure 2-2 and Figure 2-5, you saw the Generate App Bundle option. If it’s set to Never, a bundle package file will not be produced. However, if it’s set to Always or Needed, the MakeAppx.exe tool is passed a “bundle” switch telling it to create an .appxbundle package file (if you have resources). This file is just another ZIP file containing its own XML manifest file as well as other .appx package files. The schema for the .appxbundle package file’s XML manifest file can be found at http://msdn.microsoft.com/en-us/library/windows/apps/dn263100.aspx. There will be one .appx package for each CPU architecture you desire (x86, x64, or ARM), one .appx file for each set of language resources (en, es, fr, de, and so on), one .appx file for each resolution scale (80%, 100%, 140%, and 180%), and one .appx file for each version of DirectX you have texture maps for (dx9, dx10, and dx11).

What you upload to the WIndows Store is this one .appxbundle package file. Then, when a user goes to install your package, the system detects the user’s CPU and installs the .appx package containing the matching code. Then the system detects the user’s installed languages, monitors, and video card and installs just the .appx package files the user requires. The remaining .appx package files are not downloaded and installed. This saves time and disk space.

At any time, you can modify a resource or your app and use the Create App Packages wizard to create a new version of the .appxbundle package file. You then upload the new version of the package file to the Windows Store. About once a day, each user’s PC checks the WIndows Store to see if a new version of the bundle package file exists and, if so, the PC downloads any of the blocks that have changed. (Remember the discussion of the block map in the previous section.) This keeps the parts of your package that are relevant to the user up to date on each user’s PC.

Also, sometime in the future, a user might install another language, change the monitor, or upgrade a video card. Within a day of these changes, the system detects this and automatically installs any of the bundle package’s embedded .appx resource packages that are now relevant to the user; any now-irrelevant .appx packages are uninstalled. The user can force an update by going to the Store app’s Settings charm > App Updates pane and then tapping the Check For Updates button.

Important

The primary .appx package containing code must have a complete set of resources embedded inside it. That is, you cannot have any resource in an .appx resource package that is not also in the primary package. The reason is obvious: if you have a resource in a German language package, a user who does not get the German language package installed cannot run the app successfully. The primary packages (one for each CPU architecture) must have one set of resources that act as a fallback should more specific resources not be available.

Deploying a Windows Store package

A Windows Store package can be deployed (installed) to a user’s PC using three different techniques. The technique you use depends on the reach—that is, how many installs you anticipate. Here are the three reach categories and descriptions of when you use each one:

  • Restricted deployments. Use restricted deployments when you want to deploy a package to a small set of people. Typically, you use this technique for testing scenarios or when you want to give your package to some friends or family members for evaluation.

  • Enterprise deployments. Use this technique when you want to make a package installable by members of your company or enterprise but not to the public at large. This technique is typically used for packages containing an app that performs functions related to a company’s way of doing business. This technique is frequently referred to as sideloading.

  • Windows Store deployments. Use this technique when you want to make your package available to the general public. Once your package is deployed to the Windows Store, anyone running Windows can install your package via the built-in Windows Store app. See Chapter 11 for more information about the Windows Store.

The next three sections examine these three techniques in detail.

Restricted deployments

Table 2-4 showed the files produced by Visual Studio’s Create App Packages wizard. You can copy these files to another PC and install the package by running the Add-AppxDevPackage.ps1 PowerShell script. This script performs the following actions:

  1. Prompts the user to acquire a developer license (if one is not already installed) by running the Show-WindowsDeveloperLicenseRegistration PowerShell script.

  2. Installs the package’s certificate (.cer file) in the PC’s Trusted People store by running the CertUtil.exe utility.

  3. Unzips the package’s contents (and any dependent framework packages) to a directory on the user’s PC by running the Add-AppxPackage PowerShell script.

Developer licenses are free, but to get one, the machine must have an Internet connection and the user must have a Microsoft account. Also, developer licenses do expire (approximately every 30 to 90 days), so they must periodically be renewed for the installed package to continue working. The prompt to acquire a developer license explicitly mentions that you can use the license only for developing, testing, and evaluating apps. When a developer license expires, packages that require it fail to execute. On the Start screen, a small cross sign is displayed in the lower-right corner of an app’s tile.

In the second step, the package’s certificate is installed in the PC’s Trusted People certificate store. PowerShell warns you that this entails serious security risks because the system will now trust any package signed with this certificate. When this certificate expires, Windows also prevents the package from executing on the user’s PC.

In the last step, the system unzips the .appx file’s contents into a directory under %ProgramFiles%WindowsApps. The directory name matches the package full name, which includes the version number of the package. This means that different versions of the same package can be installed side-by-side on a single PC. This is useful if one user on the PC wants to run version 1.2.3.4 while another user is still using version 1.0.0.0.

The WindowsApps directory is a hidden directory, and its security settings prevent you from browsing it. However, the security settings are such that you can look inside one of WindowsApps’ subdirectories. For example, you can navigate to %ProgramFiles%WindowsAppsMicrosoft.Bing_1.2.0.137_x64__8wekyb3d8bbwe and see this package’s unzipped contents. Also, Wintellect’s Package Explorer Desktop app (discussed later) can enumerate all packages installed by the current user.

At this point, the package is installed and integrated with the operating system. The user can go to the Start screen or App view screen and launch the package’s app until either the developer license or the package’s certificate expires.

Enterprise deployments

Many companies produce line-of-business (LOB) or enterprise (B2B) apps whose sole purpose is to be used by employees or partners of the company. For these kinds of apps, it would be too much of a burden to have all users install and periodically renew developer licenses. In addition, the developer license is for the purpose of app evaluation. For LOB apps, a company would not want to post its internal business apps in the Windows Store where anyone could install them. To install a package containing an enterprise app, Windows allows sideloading.

To sideload a package, the enterprise must obtain a Software Publisher Certificate (SPC) from a trusted certificate authority. Windows trusts many certificate authorities without any additional configuration. If your package’s certificate is from one of these already trusted authorities, you don’t need to deploy and manage additional certificates to the targeted Windows PCs. Alternatively, you can use a certificate from your company’s internal Certificate Authority (CA) to sign your package. If you choose this option, your IT administrators need to deploy this CA certificate on the targeted Windows PCs. In Visual Studio’s manifest designer, you can click the Packaging tab and then click the Choose Certificate button to select your company’s SPC, ensuring that your .appx package file is signed with this SPC. Now the employees’ PCs will trust packages signed with this certificate.

In addition to your package being signed with a trusted certificate, machines require the AllowAllTrustedApps Group Policy setting be enabled. (See http://technet.microsoft.com/en-us/library/hh852635.aspx.)

Finally, the PC must be domain-joined and running Windows Enterprise edition or any of the Windows Server editions. Or, if the PC is not domain-joined or running another edition of Windows (such as Windows, Windows Pro, or Windows RT[17]), your company must acquire Enterprise Sideloading keys (part number: J7S-00005) from the Microsoft Volume Licensing Service Center (VLSC) website at (https://www.microsoft.com/licensing/servicecenter/default.aspx). These licenses never expire.

Customers with Software Assurance for Windows or Windows Virtual Desktop Access (VDA) subscriptions in the following Volume Licensing programs will be granted Enterprise Sideloading keys at no additional cost:

  • Enterprise Agreement with Windows

  • Enterprise Subscription Agreement with Windows

  • Enrollment for Education Solutions with Windows

  • Campus and School Agreement with Windows

  • Select and Select Plus with Software Assurance for Windows

Other customers can purchase Enterprise Sideloading keys in packs of 100 through Volume Licensing. Enterprise Sideloading keys are available for purchase in the following programs:

  • Select and Select Plus

  • Open License

Unfortunately, you must purchase Enterprise Sideloading keys in packs of 100. This means that Microsoft provides no cost-effective way of unlocking just a few machines for family, friends, or small businesses. This is a pretty big change from how the Window ecosystem worked in the past with respect to deploying Windows applications. With Windows Store apps, Microsoft wants to enforce a managed environment where packages are verified by Microsoft before they can be installed on users’ PCs. This gives Windows users confidence in their PCs and, more importantly, their data. So, while enterprise sideloading makes it possible to bypass the Windows Store, potentially opening up users’ PCs and data to mischief, Microsoft is purposely making this difficult to do and hopes that enterprise sideloading is the exception to the rule.

When you have the certificate, Group Policy, and Enterprise Sideloading key issues sorted out, actually deploying a package is easy: just run the PowerShell script. Additionally, IT administrators can provision Windows images with apps using Deployment Image Servicing and Management. (See http://technet.microsoft.com/en-us/library/hh852134.aspx.) Packages can also be sideloaded using Windows InTune and System Center Configuration Manager. These two Microsoft offerings have additional costs associated with them. However, a Microsoft employee has created a free Windows Store app (with source code) you can use; see http://companystore.codeplex.com/.

An additional benefit of deploying in an enterprise is that packages can be preconfigured with initial data such as configuration settings, database connection strings, and so on. For this, you will have to write a small desktop application that calls Windows.Management.Core.ApplicationDataManager’s CreateForPackageFamily method to gain access to the package’s data directories. Wintellect’s Package Explorer Desktop app uses this API.

Windows Store deployments

This method of deployment is by far the most important, and Chapter 11 is dedicated to covering the Windows Store in great detail. This section focuses on the mechanics of deploying an app via the Windows Store.

After reserving a name for your package via the Windows Store dashboard, you use Visual Studio’s Associate Your App With The Store menu item to associate your package with the reserved package name. Once you’ve done this, Visual Studio creates a temporary untrusted signing certificate of which the subject is now a GUID (assigned by the Windows Store). This GUID is your Publisher ID, and it uniquely identifies you as the publisher when you registered your individual or business account with the Windows Store. In your package’s manifest file, Visual Studio updates the Package Name, Package Display Name, Publisher, Publisher Display Name, and Application Display Name. Of course, the Package Family Name and Package Full Name are also updated to reflect the new Publisher ID value (GUID).

When you finish developing and testing your app, you upload your final .appxupload file to the Windows Store via the dashboard. Then Microsoft tests your app. After it passes certification, the Windows Store signs your package file with a Windows Store certificate where your Publisher ID GUID is the subject. The Windows Store certificate is already installed on all Windows PCs (which is why it is not necessary to have a developer license or Enterprise Sideloading key installed on users’ PCs).

Now when a user downloads your package from the Windows Store, Windows unzips the package’s contents into the %ProgramFiles%WindowsApps directory, registers the package’s app with the system for the current user, and the user can now launch the app.

Package staging and registration

The previous section explored the various ways of deploying a package to a user’s PC. In this section, we explore how a package integrates itself with the system, allowing a user to activate the package’s app. Specifically, we’ll talk about staging and registration. Packages are staged once per PC and are registered once per user profile. Note that packages downloaded from the Windows Store are licensed to a user’s Microsoft account but they are staged to the user’s account on the PC. Usually, these are one and the same; that is, a user has linked her PC account with her Microsoft account. However, they do not have to be the same. In fact, a user can go to the Store app, display the Settings charm > Your Account pane, and change the Microsoft account she used to download packages from the WIndows Store. I do this when I want to install a package I have already purchased on another family member’s PC (where that family member logs in as himself).

Staging occurs when Windows unzips the package file’s contents into the %ProgramFiles%WindowsAppsPackageFullName directory. You’ll notice that Windows uses the package full name, which includes the package’s version number. This allows the system to have different versions of the same app installed side by side on a single PC under the %ProgramFiles%WindowsApps directory. Because the content of this folder is read-only, it can be shared by all users on a PC. The system keeps older versions of the package until all users have either uninstalled or upgraded away from the older version. When a particular version of a package is uninstalled, the subdirectory for the package is completely destroyed, ensuring that the package leaves no footprint behind.

Registration occurs when a user installs a package for himself. During registration, Windows adds entries in the registry for the package. For example, it adds the package under this key:

HKCUSoftwareClassesActivatableClassesPackagePackageFullName

This key contains child nodes with information such as the full path to the package’s app’s executable and entry point. Additionally, Windows registers each app’s declared activation types (contracts). All apps must implement the Launch activation, and Windows registers that here:

HKCUSoftwareClassesExtensionsContractIdWindows.Launch

For those of you familiar with COM, you’ll recognize some concepts.

During registration, Windows also creates a directory for the package’s per-user state. This directory is created here:

%UserProfile%AppDataLocalPackagesPackageFamilyName

Package state and storage folders are discussed in Chapter 4 and in “Chapter 5. Unlike the %ProgramFiles%WindowsAppsPackageFullName directory created during staging, this directory uses the package’s family name instead of the package’s full name. The package family name does not include the version number. The system does not need the version number for the package’s data, because a user can use only one version of a package at a time. Therefore, while a PC can have multiple versions of a package installed for different users at the same time, an individual user will have only one version of the package installed for himself. This also means that if a user upgrades to a new version of a package, the user’s per-package data remains on the PC and is accessible by a newer version of the package. Of course, if the user uninstalls a package, the package gets unregistered for that user. This causes all the user’s per-package data and registry settings to be completely destroyed, ensuring that the package leaves no footprint behind for that particular user.

If you are experiencing issues with deployment, registration, or staging, examine the following Windows event log locations:

  • Application And Services Logs > Microsoft > Windows > AppXDeployment

  • Application And Services Logs > Microsoft > Windows > AppXDeployment-Server

  • Application And Services Logs > Microsoft > Windows > AppXPackagingOM

Wintellect’s Package Explorer desktop app

From the accompanying source code (see http://wintellect.com/Resource-WinRT-Via-CSharp), you can download the Wintellect Package Explorer. (See Figure 2-7.) This app is a very useful utility for exploring all the packages installed by the current user. It also allows you to explore a package’s data, navigate to its directories, launch its apps, and uninstall packages. It also shows the capabilities and declarations enabled by all the installed packages. The tool also shows the package’s local and roaming settings in the bottom pane.

Wintellect’s Package Explorer utility.

Figure 2-7. Wintellect’s Package Explorer utility.

Without going into the details of Package Explorer’s implementation, here are some of the methods it uses:

  • It uses PackageManager’s static FindPackagesForUser method to get all the installed packages. PackageManager also has methods to add and remove packages from the PC.

  • It uses ApplicationDataManager’s static CreateForPackageFamily method to access each package’s data. You can see the package data displayed in the bottom pane of Figure 2-7.

  • Package Explorer is able to launch apps by calling IApplicationActivationManager’s ActivateApplication. This is a COM interface you can use from desktop apps to launch Windows Store apps given their AppUserModelID string.

Most of these methods are callable only from a Windows desktop app because these APIs require standard user privileges and Window Store apps don’t have these within their app container. It is unlikely you would need any of these APIs for your Windows Store app development.

Debugging Windows Store apps

This last section presents some general information about debugging a Windows Store app with Visual Studio. Other chapters in this book give additional debugging tips and tricks.

When you use Visual Studio to build and debug your app, Visual Studio creates all your package’s files under your project’s build directory; the files are not zipped into an .appx package file; therefore, nothing is signed with a certificate and no package is installed under the %ProgramFiles%WindowsApps directory. The app runs directly from the project’s output directory. This means that the app is registered for the user, but the app was never actually staged onto the machine. Wintellect’s Package Explorer displays “Development” in the “Type” column for any packages that are registered and not staged.

Of course, if you just delete the files from the project’s output directory, the app will no longer work but the app is still registered with the system. Attempting to launch the app via a Start tile immediately fails, returning you right back to the Start screen again. If you select the app and then tap Uninstall, the package will officially be unregistered, meaning that all the app’s footprint for the user is destroyed but the package doesn’t really get uninstalled because it was never actually staged.

When you make changes to your app in Visual Studio, rebuild it, and rerun it, any per-package data (discussed in Chapter 4) remains on your machine. This is usually desirable because you can run your app, create some state, fix a bug, and then test the fix against the old state. However, in some circumstances, Visual Studio will automatically unregister and reregister your app, thereby deleting any per-package data. Visual Studio does this if you run the app from a different disk location (for example, switching from a Debug build to a Release build), change the XML manifest file, or change certain files (such as Start screen logos). Sometimes, while debugging and testing, you might want to force Visual Studio to delete any per-package data each time you run your app. Visual Studio enables this via its Uninstall And Then Re-Install My Package check box, which is available to you when you look at your project’s debug settings. (See Figure 2-8.)

Visual Studio’s Debug properties pane showing the various start options.

Figure 2-8. Visual Studio’s Debug properties pane showing the various start options.

In Figure 2-8, you also see that there are different options for Target Device: Simulator, Local Machine, and Remote Machine. You can change the target in the Debug toolbar next to the Play button, or you can change it in the project’s properties under the Debug tab. The default Target Device is Local Machine, and this will just register, run, and attach the debugger to your app in your local logon session. A second option is to use Simulator. Selecting this will result in a simulated tablet system, as you see in Figure 2-9.

The simulator provides a set of options in the border on the right. These allow you to simulate touch gestures such as tap, pinch and stretch, and rotate. You can also rotate the simulator’s screen in 90-degree increments. An especially interesting feature of the simulator is that you can use it to check how your app would look on PCs with different screen sizes and dots per inch (DPI) settings. The remaining buttons allow you to simulate a change of geo-location, take screen shots of your app, and simulate different network conditions.[18]

You close the simulator by selecting Settings charm > Power > Disconnect or by displaying its context menu via its icon on the desktop taskbar and then selecting Close Window. But, to improve launching a debugging session, leave the simulator running between launches of your app.

The simulator window with an app running inside of it.

Figure 2-9. The simulator window with an app running inside of it.

In addition to debugging on the local PC and via the simulator, you can also debug your app when it is running remotely on another physical PC. On the remote PC, you will have to install the Remote Tools for Visual Studio, downloadable from here: http://www.microsoft.com/visualstudio/eng/downloads. There is a version for x86, x64, and ARM, and this is the only way you can debug on ARM architectures because there is no ARM version of Visual Studio.



[15] The Windows Store has one exception to this policy. The “Mail, Calendar, and People” package contains the three apps that ship with Windows itself.

[16] You also can create packages that have no apps in them at all. These packages are called framework packages. Examples of framework packages are the Windows Library for JavaScript apps, Microsoft Visual C++ Runtime, and Microsoft PlayReady Content Protection Framework.

[17] Windows RT PCs that run on ARM chips can’t join a domain; these PCs require Enterprise Sideloading keys to sideload packages.

[18] The simulator is implemented as a terminal services remote app. You can see in Task Manager’s User tab that running the simulator results in an additional logon session. Because this additional session can lead to additional instances of apps running under the same user, some desktop apps might show unexpected behavior when the simulator is running. In addition, beware that deleting any files in the simulator actually deletes the files from your host system!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.103.28