WiX: A Developer's Guide to Windows Installer XML - Nick Ramirez - E-Book

WiX: A Developer's Guide to Windows Installer XML E-Book

Nick Ramirez

0,0
39,59 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

WiX is an open source project and a toolset that builds Windows installation packages from XML source code. WiX, which is used internally by Microsoft and by many companies around the World, simplifies many of the installation tasks that used to be shrouded in mystery. The tool set provides a command-line environment that you can integrate into your old-style build processes or you can use the newer technology from inside integrated development environments to build your setup packages. You'll find that you understand your installer better, can create it in less time, and save money in the process. No one really wants to devote a lifetime to understanding how to create a hassle-free installer for any software.

This hands-on guide takes the mystery out of Windows Installer by showing how simple XML elements can be leveraged to create a sophisticated install package. By relying on Microsoft standards, you'll be able to use features like Property elements to customize your application's entry in Add/Remove Programs, the Shortcut element to create Start menu shortcuts, and other specialized elements for building upgrade and patch support and more.

This book will show you the fundamental ingredients needed to build a professional-grade installer using Windows Installer XML. The initial chapters will introduce you to the set of required elements necessary to build a simple installer. We'll then explore those basic elements in more detail and see how best to use them in the real world.In the ensuing chapters, you'll move on to learn about adding conditions that alter what the user can install, then how to add actions to the install sequence and how to author a user interface. We'll move on to advanced topics such as editing data in the Windows Registry, installing a Windows service, and building your project from the command line. Finally, you'll learn to localize your package for different languages and detect older versions during upgrades. Each chapter uses to-the-point examples to illustrate the best way to use the language.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB

Seitenzahl: 361

Veröffentlichungsjahr: 2010

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

WiX: A Developer's Guide to Windows Installer XML
Credits
About the Author
About the Reviewer
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Errata
Piracy
Questions
1. Getting Started
Introducing Windows Installer XML
What is WiX?
Is WiX for you?
Where can I get it?
Votive
A word about GUIDs
Your first WiX project
XML declaration and Wix element
Product element
Package element
Media element
Directories
Components
Files
Features
Start Menu shortcuts
Putting it all together
Adding a User Interface
Viewing the MSI database
Orca.exe
Turning logging on during installation
Other resources
Summary
2. Creating Files and Directories
File element
DirectoryRef element
ComponentGroup element
Fragment element
Harvesting files with heat.exe
Copying and moving files
Copying files you install
Copying existing files
Moving existing files
Installing special-case files
Adding assembly files to the GAC
Installing a TrueType font
Creating an empty folder
Setting file permissions
Speeding up file installations
Summary
3. Putting Properties and AppSearch to Work
Custom properties
Declaring and setting properties
Referencing properties
Property visibility and scope
Secure properties
Property datatypes
Predefined Windows Installer properties
Implied properties
Cited properties
AppSearch
DirectorySearch
FileSearch
ComponentSearch
RegistrySearch
IniFileSearch
Summary
4. Improving Control with Launch Conditions and Installed States
Conditions
Condition syntax
Launch conditions
Feature conditions
Component conditions
Action state
Installed state
Summary
5. Understanding the Installation Sequence
InstallUISequence
UI standard actions
AppSearch
LaunchConditions
ValidateProductID
CostInitialize
FileCost
CostFinalize
ExecuteAction
InstallExecuteSequence
Execute standard actions
InstallValidate
InstallInitialize
ProcessComponents
UnpublishFeatures
RemoveRegistryValues
RemoveShortcuts
RemoveFiles
InstallFiles
CreateShortcuts
WriteRegistryValues
RegisterUser
RegisterProduct
PublishFeatures
PublishProduct
InstallFinalize
Immediate vs. deferred
Custom actions
Set a Windows Installer Property
Set the location of an Installed Directory
Run embedded VBScript or JScript
Call an external VBScript or JScript file
Call a function from a dynamic-link library
Trigger an executable
Send an error that stops the installation
Rollback custom actions
Accessing properties in a deferred action
Adding conditions to custom actions
Deployment Tools Foundation
Session object
Getting and setting properties
Logging
Showing a MessageBox
Accessing feature and component states
Querying the MSI database
Inserting rows into the MSI database
Summary
6. Adding a User Interface
WiX standard dialog sets
WixUI_Advanced
WixUI_FeatureTree
WixUI_InstallDir
WixUI_Mondo
Customizing a standard dialog set
Creating your own dialogs
ICE20 errors
Adding dialog files
Scheduling dialogs
Dialog element
Adding TextStyle elements
Adding a tabbable control
Adding a progress dialog
Modal windows
ICE20 revisited
FilesInUse
Error
FatalError
UserExit
Exit
Summary
7. Using UI Controls
Controls
PushButton
Text
ScrollableText
Line
GroupBox
Bitmap
Icon
Edit
MaskedEdit
PathEdit
CheckBox
RadioButtonGroup
ComboBox
ListBox
ListView
DirectoryList
DirectoryCombo
SelectionTree
VolumeCostList
VolumeSelectCombo
Billboard
ProgressBar
Summary
8. Tapping into Control Events
Publish element
Subscribe element
Publish events
AddLocal
DoAction
EndDialog
NewDialog
Publishing a property
Subscribe events
ScriptInProgress
SelectionAction
TimeRemaining
Summary
9. Working from the Command Line
Candle.exe
Command-line arguments (compiling)
-arch
-d
-ext
-fips
-I
-nologo
-o
-p
-pedantic
-sfdvital
-ss
-sw
-trace
-v
-wx
Response files
.wixobj files
Compile-time variables
Environment variables
System variables
Custom variables
Preprocessor extensions
Conditional statements and iterations
if...elseif...else
ifdef
ifndef
Iterations
Errors and warnings
Light.exe
Command-line arguments (linking)
-ai
-b
-bf
-binder
-cultures
-d
-dut
-ext
-loc
-nologo
-notidy
-o[ut]
-pedantic
-sadmin
-sadv
-sloc
-sma
-ss
-sts
-sui
-sv
-sw[N]
-usf <output.xml>
-v
-wx[N]
-xo
Command-line arguments (binding)
-bcgg
-cc <path>
-ct <N>
-cub <file.cub>
-dcl:level
-eav
-fv
-ice<ICE>
-pdbout <output.wixpdb>
-reusecab
-sa
-sacl
-sf
-sh
-sice:<ICE>
-sl
-spdb
-sval
Link-time variables
Localization variables
Binder variables
Custom variables
Building an installer without Visual Studio
Summary
10. Accessing the Windows Registry
Reading from the Registry
Writing to the Registry
RegistryValue
RegistryKey
Setting NeverOverwrite
Removing Registry values
RemoveRegistryKey
RemoveRegistryValue
Copying Registry values
Registry permissions
Summary
11. Controlling Windows Services
Creating a simple Windows service
Using sc.exe
Using WiX to install a service
Starting, stopping, and uninstalling a service
Setting the service's user account
Adding service dependencies
Service recovery with Util:ServiceConfig
Summary
12. Localizing Your Installer
Setting language and code page attributes
Package element
Product element
WiX localization files
The role of Light.exe
Localizing error messages
Localizing the EULA
Creating a multi-language MSI
Summary
13. Upgrading and Patching
Planning for updates
Choosing an update type
Per-user or per-machine
Major upgrade
Minor upgrade
Authoring a patch file
Building the patch on the command line
Small update
Summary

WiX: A Developer's Guide to Windows Installer XML

WiX: A Developer's Guide to Windows Installer XML

Copyright © 2010 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: October 2010

Production Reference: 1131010

Published by Packt Publishing Ltd.

32 Lincoln Road

Olton

Birmingham, B27 6PA, UK.

ISBN 978-1-849513-72-2

www.packtpub.com

Cover Image by Asher Wishkerman ( <[email protected] >)

Credits

Author

Nick Ramirez

Reviewer

Martin Oberhammer

Acquisition Editor

Eleanor Duffy

Development Editor

Dhiraj Chandiramani

Technical Editors

Vanjeet D'souza

Kavita Iyer

Harshit Shah

Indexer

Tejal Daruwale

Editorial Team Leader

Akshara Aware

Project Team Leader

Priya Mukherji

Project Coordinator

Jovita Pinto

Proofreader

Lynda Sliwoski

Production Coordinator

Melwyn D'sa

Cover Work

Melwyn D'sa

About the Author

Nick Ramirez is a software engineer working at Sophos in Columbus, Ohio. He previously worked with open source solutions like Linux and PHP before moving to C#, WiX, and other Windows technologies. As a member of the engineering team, he has helped to develop install code for the company's enterprise software.

I would like to thank especially my fiancée, Heidi, for her patience while I worked on this book. I'd also like to thank the Packt team for their hard work and guidance along the way. Another big thanks to Martin Oberhammer and Neil Sleightholm for their WiX expertise and help in filling in the gaps

About the Reviewer

Martin Oberhammer was born on December 25, 1975 in Italy. In 1995 he moved to Linz in Austria, where he studied computer science at the Johannes Kepler University and graduated in October 2002.

Martin worked at the Ars Electronica Center in Linz during his study. Together with artists, he created virtual realities for the CAVE. In May 2003 he started working for Utimaco Safeguard AG in Linz and developed advanced authentication techniques, like smart cards, for Microsoft Windows systems. He also made his first experiences in deploying software. The company transferred him to Foxboro, MA in USA in August 2008. Among other things he created setups using WiX technology. He moved to Columbus, OH in October 2009 and started working for Sophos Inc., where he continues creating setups.

Preface

Since Rob Mensching offered up the WiX toolset as the first open source project from Microsoft in 2004, it has been quietly gaining momentum and followers. Today, thousands use it to build Windows Installer packages from simple XML elements. Gone are the days when you would have had to pay for software to build an installer for you. Now, you can do it yourself for cheap.

Not only that, but WiX has matured into a fairly slick product that's sufficiently easy to use. Best of all, it has all of the bells and whistles you want including the functionality to add user interface wizards, Start Menu shortcuts, control Windows services, and read and write to the Registry.

WiX: A Developer's Guide to Windows Installer XML gives you the knowledge to start building sophisticated installers right away, even if you have no prior experience doing so. Each chapter gets straight to the point, giving you hands on experience, so you'll master the technology quickly.

What this book covers

Chapter 1, Getting Started, explains how after downloading and installing the WiX toolset, you'll start using it right away to create a simple installer. Then, you'll see how to add a basic user interface to it, install it with logging turned on, and view its internal database.

Chapter 2, Creating Files and Directories, gives you deeper understanding of how files are installed and what is the best way to organize them in your project. You'll then use the tool heat.exe to generate WiX markup. Last, you'll learn about copying and moving files, and installing special-case files.

Chapter 3, Putting Properties and AppSearch to Work, gets you introduced to Windows Installer properties as you create your own and use those that are built in. Later, you'll check the end user's computer for specific files, directories, Registry keys, and INI file settings using AppSearch.

Chapter 4, Improving Control with Launch Conditions and Installed States, allows you to leverage conditional statements to set prerequisites for running your installer and to exclude particular features or components from the install. You'll also discover how to check the action and installed state of your features and components.

Chapter 5, Understanding the Install Sequence, allows you to get a clear picture of how the whole installation process works as you examine the order and meaning of installer actions. You will then create custom actions and add them to this built-in sequence to extend the functionality. Then, you'll learn the basics of using the Deployment Tools Foundation library for writing custom action code in C#.

Chapter 6, Adding a User Interface, after giving you a quick introduction to the standard dialog wizards that come with the WiX toolset, allows you to start building your own from scratch. You'll learn all of the required elements to display dialogs and to link them together. You'll also see how to build dialogs for displaying errors and user exits.

Chapter 7, Using UI Controls, gives you hands on experience with each type of UI control including buttons, textboxes, and progress bars.

Chapter 8, Tapping into Control Events, breathes life into your UI controls by having them publish and subscribe to events.

Chapter 9, Working from the Command Line, compiles your code from the command line and then links and binds object files into an MSI. You'll learn to use preprocessor variables and conditional statements and how to create custom preprocessor extensions.

Chapter 10, Accessing the Windows Registry,allows you to read from the Windows Registry and add keys and values to it at install time. You'll also learn how to remove existing keys, copy values, and set permissions.

Chapter 11, Controlling Windows Services, installs Windows services and issues start, stop, and remove commands to them. You'll learn to set the service's user account, add service dependencies, and set failure recovery.

Chapter 12, Localizing Your Installer, creates localized installers for different languages and teaches how light.exe, the WiX linker, plays a role. You'll then learn how to make a single multi-language installer.

Chapter 13, Upgrading and Patching, allows you to learn how to plan for and implement a major upgrade of your product and how to make small updates using patch files.

What you need for this book

In order to both write and run the code demonstrated in this book, you will need the following:

Visual Studio 2005 or newer (Standard edition or higher)The WiX toolset, which can be downloaded from http://wix.codeplex.com/

Who this book is for

If you are a developer and want to create installers for software targeting the Windows platform, then this book is for you. You'll be using a lot of XML so that you get accustomed to the basics of writing well-formed documents, using XML namespaces and the dos and don'ts of structuring elements and attributes. You should know your way around Visual Studio, at least enough to compile projects, add project references, and tweak project properties. No prior knowledge of Windows Installer or WiX is assumed.

Conventions

In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.

Code words in text are shown as follows: "We can include other contexts through the use of the include directive."

A block of code is set as follows:

<Component Id="CMP_MyProgramEXE" Guid="E8A58B7B-F031-4548-9BDD-7A6796C8460D"> <File Id="FILE_MyProgramEXE" Source="MyProgram.exe" Name="NewName.exe" KeyPath="yes" /> </Component>

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

File Id="FILE_MyProgramEXE" Source="$(var.FilesPath)MyProgram.exe" KeyPath="yes" />

Any command-line input or output is written as follows:

Light.exe -loc en-us.wxl -loc en-us2.wxl -loc de-de.wxl -cultures:en-us "*.wixobj" -out myInstaller.msi

New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes for example, appear in the text like this: "Use the Add Reference option in your Solution Explorer".

Note

Warnings or important notes appear in a box like this.

Tip

Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply send an e-mail to <[email protected]>, and mention the book title via the subject of your message.

If there is a book that you need and would like to see us publish, please send us a note in the SUGGEST A TITLE form on www.packtpub.com or e-mail <[email protected]>.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Tip

Downloading the example code for this book

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.

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/support, selecting your book, clicking on the erratasubmissionform link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors, and our ability to bring you valuable content.

Questions

You can contact us at <[email protected]> if you are having a problem with any aspect of the book, and we will do our best to address it.

Chapter 1. Getting Started

Windows Installer XML (WiX) is a free XML markup from Microsoft that is used to author installation packages for Windows-based software. The underlying technology is Windows Installer, which is the established standard for installing desktop-based applications to any Windows operating system. It is used by countless companies around the world. Microsoft uses it to deploy its own software including Microsoft Office and Visual Studio. In fact, Microsoft uses WiX for these products.

Windows Installer has many features, but how do you leverage them? How do you even know what they are? This book will help you by making you more familiar with the wide range of capabilities that are available. WiX makes many of the arcane and difficult to understand aspects of Windows Installer technology simple to use. This book will teach you the WiX syntax so that you can create a professional-grade installer that's right for you.

In this chapter, we will cover the following:

Getting WiX and using it with Visual StudioCreating your first WiX installerExamining an installer database with OrcaLogging an installation processAdding a simple user interface

Introducing Windows Installer XML

In this section, we'll dive right in and talk about what WiX is, where to get it, and why you'd want to use it when building an installation package for your software. We'll follow up with a quick description of the WiX tools and the new project types made available in Visual Studio.

What is WiX?

Although it's the standard technology and has been around for years, creating a Windows Installer, or MSI package, has always been a challenging task. The package is actually a relational database that describes how the various components of an application should be unpacked and copied to the end user's computer.

In the past you had two options:

You could try to author the database yourself—a path that requires a thorough knowledge of the Windows Installer API.You could buy a commercial product like InstallShield to do it for you. These software products will take care of the details, but you'll forever be dependent on them. There will always be parts of the process that are hidden from you.

WiX is relatively new to the scene, offering a route that exists somewhere in the middle. Abstracting away the low-level function calls while still allowing you to write much of the code by hand, WiX is an architecture for building an installer in ways that mere mortals can grasp. Best of all, it's free. As an open source product, it has quickly garnered a wide user base and a dedicated community of developers. Much of this has to do not only with its price tag but also with its simplicity. It can be authored in a simple text editor (such as Notepad) and compiled with the tools provided by WiX. As it's a flavor of XML, it can be read by humans, edited without expensive software, and lends itself to being stored in source control where it can be easily merged and compared.

The examples in this first chapter will show how to create a simple installer with WiX using Visual Studio. However, later chapters will show how you can build your project from the command line using the compiler and linker from the WiX toolset. The WiX source code is available for download, so you can be assured that nothing about the process will be hidden if you truly need to know.

Is WiX for you?

To answer the question "Is WiX for you?" we have to answer "What can WiX do for you?" It's fairly simple to copy files to an end user's computer. If that's all your product needs, then the Windows Installer technology might be overkill. However, there are many benefits to creating an installable package for your customers, some of which might be overlooked. Following is a list of features that you get when you author a Windows Installer package with WiX:

All of your executable files can be packaged into one convenient bundle, simplifying deployment.Your software is automatically registered with Add/Remove Programs.Windows takes care of uninstalling all of the components that make up your product when the user chooses to do so.If files for your software are accidently removed, they can be replaced by right-clicking on the MSI file and selecting Repair.You can create different versions of your installer and detect which version has been installed.You can create patches to update only specific areas of your application.If something goes wrong while installing your software, the end user's computer can be rolled back to a previous state.You can create Wizard-style dialogs to guide the user through the installation.

Many people today simply expect that your installer will have these features. Not having them could be seen as a real deficit. For example, what is a user supposed to do when they want to uninstall your product but can't find it in the Add/Remove Programs list and there isn't an uninstall shortcut? They're likely to remove files haphazardly and wonder why you didn't make things easy for them.

Maybe you've already figured that Windows Installer is the way to go, but why WiX? One of my favorite reasons is that it gives you greater control over how things work. You get a much finer level of control over the development process. Commercial software that does this for you also produces an MSI file, but hides the details about how it was done. It's analogous to crafting a web site. You get much more control when you write the HTML yourself as opposed to using WYSIWYG software.

Even though WiX gives you more control, it doesn't make things overly complex. You'll find that making a simple installer is very straightforward. For more complex projects, the parts can be split up into multiple XML source files to make it easier to work with. Going further, if your product is made up of multiple products that will be installed together as a suite, you can compile the different chunks into libraries that can be merged together into a single MSI. This allows each team to isolate and manage their part of the installation package.

WiX is a stable technology, having been first released to the public in 2004, so you don't have to worry about it disappearing. It's also had a steady progression of version releases. The most current version is updated for Windows Installer 4.5 and the next release will include changes for Windows Installer 5.0, which is the version that comes preinstalled with Windows 7. These are just some of the reasons why you might choose to use WiX.

Where can I get it?

You can download WiX from the Codeplex site, http://wix.codeplex.com/, which has both stable releases and source code. The current release is version 3.0. Once you've downloaded the WiX installer package, double-click it to install it to your local hard drive.

This installs all of the necessary files needed to build WiX projects. You'll also get the WiX SDK documentation and the settings for Visual Studio IntelliSense, highlighting and project templates. Version 3 supports Visual Studio 2005 and Visual Studio 2008, Standard edition or higher.

WiX comes with the following tools:

Tool

What it does

Candle.exe

Compiles WiX source files (.wxs) into intermediate object files (.wixobj).

Light.exe

Links and binds .wixobj files to create final .msi file. Also creates cabinet files and embeds streams in MSI database.

Lit.exe

Creates WiX libraries (.wixlib) that can be linked together by Light.

Dark.exe

Decompiles an MSI file into WiX code.

Heat.exe

Creates a WiX source file that specifies components from various inputs.

Melt.exe

Converts a "merge module" (.msm) into a component group in a WiX source file.

Torch.exe

Generates a transform file used to create a software patch.

Smoke.exe

Runs validation checks on an MSI or MSM file.

Pyro.exe

Creates an patch file (.msp) from .wixmsp and .wixmst files.

WixCop.exe

Converts version 2 WiX files to version 3.

In order to use some of the functionality in WiX, you may need to download a more recent version of Windows Installer. You can check your current version by viewing the help file for msiexec.exe, which is the Windows Installer service. Go to your Start Menu and select Run, type cmd and then type msiexec/? at the prompt. This should bring up a window like the following:

If you'd like to install a newer version of Windows Installer, you can get one from the Microsoft Download Center website. Go to:

http://www.microsoft.com/downloads/en/default.aspx

Search for Windows Installer. The current version for Windows XP, Vista, Server 2003, and Server 2008 is 4.5. Windows 7 and Windows Server 2008 R2 can support version 5.0. Each new version is backwards compatible and includes the features from earlier editions.

Votive

The WiX toolset provides files that update Visual Studio to provide new WiX IntelliSense, syntax highlighting, and project templates. Together these features, which are installed for you along with the other WiX tools, are called Votive. You must have Visual Studio 2005 or 2008 (Standard edition or higher). Votive won't work on the Express versions. If you're using Visual Studio 2005, you may need to install an additional component called ProjectAggregator2. Refer to the WiX site for more information:

http://wix.sourceforge.net/votive.html

After you've installed WiX, you should see a new category of project types in Visual Studio, labeled under the title WiX. To test it out, open Visual Studio and go to File | New | Project. Select the category WiX.

There are six new project templates:

WiX Project: Creates a Windows Installer package from one or more WiX source filesWiX Library Project: Creates a .wixlib libraryC# Custom Action Project: Creates a .NET custom action in C#WiX Merge Module Project: Creates a merge moduleC++ Custom Action Project: Creates an unmanaged C++ custom actionVB Custom Action Project: Creates a VB.NET custom action

Using these templates is certainly easier than creating them on your own with a text editor. To start creating your own MSI installer, select the template WiX Project. This will create a new .wxs (WiX source file) for you to add XML markup to. Once we've added the necessary markup, you'll be able to build the solution by selecting Build Solution from the Build menu or by right-clicking on the project in the Solution Explorer and selecting Build. Visual Studio will take care of calling candle.exe and light.exe to compile and link your project files.

If you right-click on your WiX project in the Solution Explorer and select Properties, you'll see several screens where you can tweak the build process. One thing you'll want to do is set the amount of information that you'd like to see when compiling and linking the project and how non-critical messages are treated. Refer to the following screenshot:

Here, we're selecting the level of messages that we'd like to see. To see all warnings and messages, set the Warning Level to Pedantic. You can also check the Verbose output checkbox to get even more information. Checking Treat warnings as errors will cause warning messages that normally would not stop the build to be treated as fatal errors.

You can also choose to suppress certain warnings. You'll need to know the specific warning message number, though. If you get a build-time warning, you'll see the warning message, but not the number. One way to get it is to open the WiX source code (available at http://wix.codeplex.com/SourceControl/list/changesets) and view the messages.xml file in the Wix solution. Search the file for the warning and from there you'll see its number. Note that you can suppress warnings but not errors.

Another feature of WiX is its ability to run validity checks on the MSI package. Windows Installer uses a suite of tests called Internal Consistency Evaluators (ICEs) for this. These checks ensure that the database as a whole makes sense and that the keys on each table join correctly. Through Votive, you can choose to suppress specific ICE tests. Use the Tools Setting page of the project's properties as shown in the following screenshot:

In this example, ICE test 102 is being suppressed. You can specify more than one test by separating them with semicolons. To find a full list of ICE tests, go to MSDN's ICE Reference web page at:

http://msdn.microsoft.com/en-us/library/aa369206%28VS.85%29.aspx

The Tool Settings screen also gives you the ability to add compiler or linker command-line flags. Simply add them to the text boxes at the bottom of the screen. We will discuss command-line arguments for Candle and Light later in the book.

A word about GUIDs

In various places throughout WiX, you'll be asked to provide a GUID, which is a Globally Unique Identifier. This is so that when your product is installed on the end user's computer, references to it can be stored in the Windows Registry without the chance of having name conflicts. By using GUIDs, Windows Installer can be sure that every software application, and even every component of that software, has a unique identity on the system.

Each GUID that you create on your computer is guaranteed to be different from a GUID that someone else would make. Using this, even if two pieces of software, both called "Amazing Software", are installed on the same computer, Windows will be able to tell them apart.

Visual Studio 2008 provides a way to create a GUID. Go to Tools | Create GUID and copy a new GUID using the Registry Format. WiX can accept a GUID with or without curly brackets around it as 01234567-89AB-CDEF-0123-456789ABCDEF or{01234567-89AB-CDEF-0123-456789ABCDEF}.

Be sure to only use uppercase letters, though. In this book, I'll display real GUIDs, but you should not reuse them as then your components will not be guaranteed to be unique.

Your first WiX project

To get started, download the WiX Toolset. It can be found at:

http://wix.codeplex.com/

Once you've downloaded and installed it, open Visual Studio and select New Project | WiX | WiX Project. This will create a solution with a single .wxs (WiX source) file. Visual Studio will usually call this file Product.wxs, but the name could be anything as long as it ends with .wxs.

Even the most minimal installer must have the following XML elements:

an XML declarationa Wix element that serves as the root element in your XML documenta Product element that is a child to the Wix element, but all other elements are children to ita Package elementa Media elementat least one Directory element with at least one child Component elementa Feature element

XML declaration and Wix element

Every WiX project begins with an XML declaration and a Wix element.

<?xml version="1.0" encoding="UTF-8"?> <Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"> </Wix>

The xmlns, or XML namespace, just brings the core WiX elements into the local scope of your document. At the bottom of the file, you'll have to close the Wix element, of course. Otherwise, it's not valid XML. The Wix element is the root element of the document. It comes first and last. All other elements will be nested inside of it.

At this point, you could also add the RequiredVersion attribute to the Wix element. Given a WiX toolset version number, such as "3.0.5419.0", it won't let anyone compile the .wxs file unless they have that version or higher installed. If, on the other hand, you're the only one compiling your project, then it's no big deal.

Product element

Next, add a Product element.

<Wix ... > <Product Id="3E786878-358D-43AD-82D1-1435ADF9F6EA" Name="Awesome Software" Language="1033" Version="1.0.0.0" Manufacturer="Awesome Company" UpgradeCode="B414C827-8D81-4B4A-B3B6-338C06DE3A11"> </Product> </Wix>

This is where you define the characteristics of the software you're installing: its name, language, version, and manufacturer. The end user will be able to see these properties by right-clicking on your MSI file, selecting Properties and viewing the Summary tab. Most of the time, these values will stay the same from one build of your project to the next. The exception is when you want to increment the software's version or indicate that it's an upgrade of a previous installation. In that case you need only change the Version, and sometimes Id, attribute. We'll talk more about upgrading previous installations later on in the book.

The Product element's Id attribute represents the so-called ProductCode of your software. It's always a unique number—a GUID—that Windows will use to uniquely identify your software (and tell if it's already installed on the computer). You can either hardcode it, like here, or just put an asterisk. That way, WiX will pick a new GUID for you each time you compile the project.

<Wix ... > <Product Id="*" Name="Awesome Software" Language="1033" Version="1.0.0.0" Manufacturer="Awesome Company" UpgradeCode="B414C827-8D81-4B4A-B3B6-338C06DE3A11"> </Product> </Wix>

The Name attribute defines the name of the software. In addition to being displayed in the MSI file's Properties page, it will also be shown in various places throughout the user interface of your installer—that is, once you've added a user interface, which we'll touch on at the end of this chapter.

The Language attribute is used to display error messages and progress information in the specified language to the user. It's a decimal language ID (LCID). A full list can be found on Microsoft's LCID page at:

http://msdn.microsoft.com/en-us/goglobal/bb964664.aspx

The previous example used "1033", which stands for "English-United States". If your installer uses characters not found in the ASCII character set, you'll also need to add a Codepage attribute set to the code page that contains those characters. Don't worry too much about this now. We'll cover languages and code pages later in the book when we talk about localization.

The Version attribute is used to set the version number of your software. It can accept up to four digits separated by periods, although the last digit is ignored by Windows Installer during operations such as detecting previously installed versions of your application. Typically, when you make a big enough change to the existing software, you'll increment the number. Companies often use the [MajorVersion].[MinorVersion].[Build].[Revision] format, but you're free to use any numbering system you like.

The Manufacturer attribute tells the user who this software is from and usually contains the name of your company. This is another bit of information that's available via the MSI file's Properties.

The final attribute to consider is UpgradeCode. This should be set to a GUID and will identify your product across version releases. Therefore, it should stay the same even when the Product ID and Version change. Windows will use this number in its efforts to keep track of all the software installed on the machine. WiX has the ability to search for previously installed versions of not only your own software but also those created by others and it uses UpgradeCode to do it. Although, technically, this is an optional attribute, you should always supply it.

Package element

Once you've defined your Product element, the next step is to nest a Package element inside. An example is shown:

<Wix ... > <Product ... > <Package Compressed="yes" InstallerVersion="301" Manufacturer="Awesome Company" Description="Installs Awesome Software" Keywords="Practice,Installer,MSI" Comments="(c) 2010 Awesome Company" /> </Product> </Wix>

Of the attributes shown in this example, only Compressed is really required. By setting Compressed to yes, you're telling the installer to package all of the MSI's resources into CAB files. Later, you'll define these CAB files with Media elements.

Technically, an Id attribute is also required, but by omitting it, you're letting WiX create one for you. You'd have to create a new one anyway since every time you change your software or the installer in any way, the "package" (the MSI file) has changed and so the ID must change. This really, in itself, emphasizes what the Package element is. Unlike the Product element, which describes the software that's in the installer, the Package element describes the installer itself. Once you've built it, you'll be able to right-click on the MSI and select Properties to see the attributes you've set here.

The InstallerVersion attribute can be set to require a specific version of msiexec.exe (the Windows Installer service that installs the MSI when you double-click on it) to be installed on the end user's computer. If they have an older version, Windows Installer will display a MessageBox telling them that they need to upgrade. It will also prevent you from compiling the project unless you also have this version installed on your own computer. The value can be found by multiplying the major version by 100 and adding the minor version. So, for version 4.5 of msiexec.exe, you'd set InstallerVersion to "405".

The rest of the attributes shown provide additional information for the MSI file's Properties window. Manufacturer is displayed in the Author text field, Description is shown as Subject, Keywords show up as Keywords, and Comments show as Comments. It's usually a good idea to provide at least some of this information, if just to help you distinguish one MSI package from another.

Media element

The files that you intend to install are bundled up into CAB files. You have the option of splitting your package into several parts or keeping it all in one. For each Media element that you add to your WiX markup, a new CAB file will be created. Generally, you should limit the number of files you put into a single CAB file to 64 K or less and no single file should be larger than 2 GB. You can find more information about the CAB file format at:

http://msdn.microsoft.com/en-us/library/ee177956(v=EXCHG.80).aspx

Media elements come nested inside the Product element alongside the Package element.

<Wix ... > <Product ... > <Package ... /> <Media Id="1" Cabinet="media1.cab" EmbedCab="yes" /> </Product> </Wix>

Each Media element gets a unique Id attribute to distinguish it in the MSI Media table. It must be a positive integer. If the files that you add to your installation package don't explicitly state which CAB file they wish to be packaged into, they'll default to using a Media element with an Id of 1. Therefore, your first Media element should always use an Id of 1.

The Cabinet attribute sets the name of the CAB file. You won't actually see this unless you set EmbedCab to no, in which case the file won't be bundled inside the MSI package. This is atypical, but might be done to split the installation files onto several disks. Even this is becoming rare in the age of 4 GB DVDs and Internet downloads. Setting EmbedCab to no will produce a visible CAB file that must be provided alongside the MSI file during an installation.

If you do choose to split the installation up into several physical disks (or even virtual ISO images), you'll want to add the DiskPrompt and VolumeLabel attributes. In the following example, I've added two Media elements instead of one. I've also added a Property element above them, which defines a variable called DiskPrompt with a value of Amazing Software-[1].

<Property Id="DiskPrompt" Value="Amazing Software - [1]" /> <Media Id="1" Cabinet="media1.cab" EmbedCab="no" DiskPrompt="Disk 1" VolumeLabel="Disk1" /> <Media Id="2" Cabinet="media2.cab" EmbedCab="no" DiskPrompt="Disk 2" VolumeLabel="Disk2" />

The Property element will be used as the text in the MessageBox the end user sees prompting them to insert the next disk. The text in the DiskPrompt attribute is combined with the text in the property's value, switched with [1], to change the message for each subsequent disk. Make sure you give this property an Id of DiskPrompt.

So that Windows will know when the correct disk is inserted, the VolumeLabel attribute must match the "Volume Label" of the actual disk, which you'll set with whichever CD or DVD burning program you use. Once you've built your project, include the MSI file and first CAB file on the first disk. The second CAB file should then be written to a second disk.

Although we haven't described the File element yet, it's used to add a file to the installation package. To include one in a specific CAB file, add the DiskId attribute, set to the Id of the corresponding Media element. The following example includes a text file called myFile.txt in the media2.cab file:

<File Id="fileTXT" Name="myFile.txt" Source="myFile.txt" KeyPath="yes" DiskId="2" />

We'll discuss the File element in more detail later on in the chapter. If you're only using one Media element, you won't need to specify the DiskId attribute on your File elements.

Directories

So, now we've defined the identity of the product, set up its package properties, and told the installer to create a CAB file to package up the things we'll eventually install. Then, how do you decide where your product will get installed to on the end user's computer? How do we set the default installation path, such as some folder under Program Files?

When you want to install to C:\ProgramFiles, you can use a sort of shorthand. There are several directory names provided by Windows Installer that will be translated to their true paths at install time. For example, ProgramFilesFolder usually translates to C:\ProgramFiles. Following is a list of these built-in directory properties:

Directory property

Actual path

AdminToolsFolder

Full path to directory containing administrative tools

AppDataFolder

Full path to Roaming folder for current user

CommonAppDataFolder

Full path to application data for all users

CommonFiles64Folder

Full path to 64-bit CommonFiles folder

CommonFilesFolder

Full path to CommonFiles folder for current user

DesktopFolder

Full path to Desktop folder

FavoritesFolder

Full path to Favorites folder for current user

FontsFolder

Full path to Fonts folder

LocalAppDataFolder

Full path to folder containing local (non-roaming) applications

MyPicturesFolder

Full path to Pictures folder

NetHoodFolder

Full path to NetHood folder

PersonalFolder

Full path to Documents folder for current user

PrintHoodFolder

Full path to PrintHood folder

ProgramFiles64Folder

Full path to 64-bit ProgramFiles folder

ProgramFilesFolder

Full path to 32-bit ProgramFiles folder

ProgramMenuFolder

Full path to ProgramMenu folder

RecentFolder

Full path to Recent folder

SendToFolder

Full path to SendTo folder for current user

StartMenuFolder

Full path to StartMenu folder

StartupFolder

Full path to Startup folder

System16Folder

Full path to 16-bit system DLLs folder

System64Folder

Full path to System64 folder

SystemFolder

Full path to System folder for current user

TempFolder

Full path to Temp folder

TemplateFolder

Full path to Template folder for current user

WindowsFolder

Full path to Windows folder

The easiest way to add your own directories is to nest them inside one of the predefined ones. For example, to create a new directory called InstallPractice inside the ProgramFiles folder, you could add it as a child to ProgramFilesFolder. To define your directory structure in WiX, use Directory elements:

<Wix ... > <Product ... > <Package ... /> <Media ... /> <Directory Id="TARGETDIR" Name="SourceDir"> <Directory Id="ProgramFilesFolder"> <Directory Id="MyProgramDir" Name="Install Practice" /> </Directory> </Directory> </Product> </Wix>

You should place your Directory elements inside of the top-level Product element. Other than that, there aren't any restrictions about exactly where inside Product they have to go. One thing to know is that you must start your Directory elements hierarchy with a Directory with an Id