What is windows installer xml

WIX – What is Windows Installer XML

The Windows Installer XML is a powerful utility for packaging a softare into an MSI file.

Announcement

If you have a software that you want make to available to others, so that they can install it on their own Windows Machine, then Microsoft recommends that you first package up your software into a single MSI file before distributing it.

Windows Installer XML (WIX) is a free open-source tool that lets you package your software into an MSI file. To create an MSI using wix, all you essentially need to do is create an xml file then feed that xml file into WIX along with all your software’s source/binary files. WIX will then handle the rest and generate the MSI file for you.

Once the MSI file has been created, you can then install the software by:

  1. Double clicking on the msi file – an install wizard pop-up will appear prompting the user for more info
  2. Run msi file from the command line – this method is often used if you want to install the software silently. With this option you can provide all the info the windows installer needs in a single command and thereby suppressing any install wizard windows popping up. Hence this approach is really useful if you want to automate software installations.

WIX is used from the command line only. However WIX is also integrated in a lot of big name IDE’s such as Visual Studio.

Here are some of benefits of packaging your software into an MSI file:

  • All your software files are can be packaged into one convenient .msi file.
  • Your software will automatically be registered with Progam and Features
  • Windows can easily uninstall your software should the user select the uninstall option in Program and Features
  • If any of your software’s file are accidently removed, then this can be fixed by right-clicking on the MSI file and select repair.
  • You can create msi file for different versions of your software and the msi package can detect which version has been installed.
  • you can create patches to update only specific areas of your application.
  • If something goes wrong during the isntall process, then the windows installer can easily roll back to a previous state.
  • You can create Install Wizard pop windows to guide user’s through the install process.

All of these benefits comes included as part of offering your software in the form of an MSI package. There are lots of MSI creation tools out there, but WIX has emerged as one of the market leaders in this space.

Before you can use WIX, you first have to install wix.

After the install, the wix install folder should contain the following exe-based commandline utilities:

[powershell]
PS C:\Program Files (x86)\WiX Toolset v3.8\bin> ls | where-Object -f <$_.name -match ".exe
$»>

Directory: C:\Program Files (x86)\WiX Toolset v3.8\bin

Mode LastWriteTime Length Name
—- ————- —— —-
-a— 28/11/2013 05:13 28672 candle.exe
-a— 28/11/2013 05:14 28672 dark.exe
-a— 28/11/2013 05:14 28672 heat.exe
-a— 28/11/2013 05:14 24576 insignia.exe
-a— 28/11/2013 05:13 32768 light.exe
-a— 28/11/2013 05:14 28672 lit.exe
-a— 28/11/2013 05:16 32768 lux.exe
-a— 28/11/2013 05:14 28672 melt.exe
-a— 28/11/2013 05:16 28672 nit.exe
-a— 28/11/2013 05:14 32768 pyro.exe
-a— 28/11/2013 05:14 49152 shine.exe
-a— 28/11/2013 05:14 28672 smoke.exe
-a— 28/11/2013 05:14 109056 ThmViewer.exe
-a— 28/11/2013 05:14 32768 torch.exe
-a— 28/11/2013 05:14 86016 WixCop.exe
[/powershell]

You can read up about these wix tools.

When creating an xml, you need to provide guid values. An easy way to do this is just use the online guid generation tool. This page also says wix can autogenerate this using *, this might be the better approach in fast moving continuous integration. Although when you do official release then you should generate the guid using the online tool and then hard code them in.

Читайте также:  Как откатить обновление windows 10 до предыдущего при запуске

Here’s what a typical main wix source xml file looks like (note this file has the extensiont “.wxs”)

All these elements, e.g. “directory element” are described in the manual. Just do word find (ctrl+f) on this page and search for “wix schema”. the childs of this node covers all this.

Also the official wix documentation has lots of hand info.

Once you have created wxs file, place this in the same folder as your source code. Open up powershell and cd to the location of your wxs file. Then run the following command:

PS C:\Users\SChowdhury\Desktop\DummyApp> ls

Mode LastWriteTime Length Name
—- ————- —— —-
-a— 26/08/2014 08:56 26 DummyDLLFile.txt
-a— 26/08/2014 09:15 1155 Product.wxs

PS C:\Users\SChowdhury\Desktop\DummyApp> & ‘C:\Program Files (x86)\WiX Toolset v3.8\bin\candle.exe’ .\Product.wxs
Windows Installer XML Toolset Compiler version 3.8.1128.0
Copyright (c) Outercurve Foundation. All rights reserved.

Product.wxs
PS C:\Users\SChowdhury\Desktop\DummyApp> ls

Mode LastWriteTime Length Name
—- ————- —— —-
-a— 26/08/2014 08:56 26 DummyDLLFile.txt
-a— 26/08/2014 12:01 6205 Product.wixobj # new file created
-a— 26/08/2014 09:15 1155 Product.wxs

PS C:\Users\SChowdhury\Desktop\DummyApp>
[/powershell]

The candle.exe will even create the wixobj file even if it encounters minor errors. If you want candle.exe to stop as soon as it encounters any small error’s then use the “pedantic” option:

[powershell]
PS C:\Users\SChowdhury\Desktop\DummyApp> & ‘C:\Program Files (x86)\WiX Toolset v3.8\bin\candle.exe’ .\Product.wxs -pedantic
Windows Installer XML Toolset Compiler version 3.8.1128.0
Copyright (c) Outercurve Foundation. All rights reserved.

Product.wxs
C:\Users\SChowdhury\Desktop\DummyApp\Product.wxs(3) : error CNDL0087 : The Product/@Id attribute’s value, ‘774cdf65-1c3a-4650-8868-b4c090e74c5a’, is a mixed-case guid. All letters in a guid value should be uppercase.
C:\Users\SChowdhury\Desktop\DummyApp\Product.wxs(3) : error CNDL0087 : The Product/@UpgradeCode attribute’s value, ‘478ebf08-ca88-4e3b-9460-2db6f6584e6e’, is a mixed-case guid. All letters in a guid value should be uppercase.
PS C:\Users\SChowdhury\Desktop\DummyApp>
[/powershell]

This time no files have been generated.
http://msdn.microsoft.com/en-us/magazine/cc163456.aspx

Puppet’s “package” resource type also handle msi natively.

WiX Toolset

What is WiX?

WiX is a set of tools that allows you to create Windows Installer-based deployment packages for your application. The WiX toolset is based on a declarative XML authoring model. You can use WiX on the command line by using the WiX tools or MSBuild. In addition, there is also a WiX Visual Studio plug-in that supports VS2005, VS2008, and VS2010. The WiX toolset supports building the following types of Windows Installer files:

  • Installer (.msi)
  • Patches (.msp)
  • Merge Modules (.msm)
  • Transforms (.mst)

WiX supports a broad spectrum of Windows Installer features. In addition, WiX also offers a set of built-in custom actions that can be used and incorporated in Windows Installer packages. The custom actions are offered in a set of WiX extensions. Some common WiX extensions include support for Internet Information System (IIS), Structured Query Language (SQL), the .NET Framework, Visual Studio, and Windows etc.

How does WiX work?

The WiX source code is written in XML format with a .wxs file extension. The WiX tools follow the traditional compile and link model used to create executables from source code. At build time, the WiX source files are validated against the core WiX schema, then processed by a preprocessor, compiler, and linker to create the final result. There are a set of WiX tools that can be used to produce different output types. For a complete list of file types and tools in WiX, see the File Types and the List of Tools sections.

See the following topics for more detailed information:

WiX system requirements

WiX supports both .NET 3.5 and 4.0 and later. WiX’s MSBuild supports requires .NET 3.5, which is not installed by default on Windows 8 and Windows Server 2012 and later. To install the .NET 3.5 feature, go to Control Panel, open Programs and Features, and choose Turn Windows features on or off. In the list of features, choose .NET Framework 3.5 (includes .NET 2.0 and 3.0) and then choose OK.

Читайте также:  Tv box linux 4pda

Создание инсталлятора с помощью WiX

Для начала — что такое WiX? Технология WiX (Windows Installer XML) представляет собой набор инструментов и спецификаций упрощающих процесс создания дистрибутивов на базе MSI (Microsoft Installer). Если объяснять проще то это обертка вокруг MSI с человеческим лицом.

На мой взгляд изучать проще всего на простых примерах. В данной статье я приведу пример простейшего инсталлятора.

Для начала поставим условия задачи — необходимо создать установочный дистрибутив, который будет содержать следующие диалоги:

Для создания дистрибутива нам понадобится сам WiX, последнюю версию которого всегда можно скачать на Source Forge. На данный момент последняя версия 3.5.0828.0.

Необходимо скачать и установить:
1. ProjectAggregator2.msi — нужен, для того, чтобы установить Votive (находится внутри дистрибутива номер 2). Который, в свою очередь, является дополнением для Visual Studio, облегчающим процесс работы с WiX (подсветка синтаксиса, IntelliSense).
2. Wix35.msi или Wix35_x64.msi (в зависимости от платформы)
3. Русский языковой файл

Итак, скачали, установили, запускаем Visual Studio. Меню File -> New Project, если все установлено правильно — появился новый раздел Windows Installer XML. Выбираем шаблон проекта Setup Project, вводим название проекта (я оставил как есть SetupProject1).

Проект будет состоять из одного файла Product.wxs с ним мы и будем работать. В моем случае файл выглядел следующим образом:

xml version =»1.0″ encoding =»UTF-8″ ? >
Wix xmlns =»http://schemas.microsoft.com/wix/2006/wi» >
Product Id =»b7bc7c6f-9a4e-4973-be84-eca8e3427c97″ Name =»SetupProject1″ Language =»1033″ Version =»1.0.0.0″ Manufacturer =»SetupProject1″ UpgradeCode =»06a81104-1e30-463d-87e1-e8a79b4c682a» >
Package InstallerVersion =»200″ Compressed =»yes»/>

Media Id =»1″ Cabinet =»media1.cab» EmbedCab =»yes»/>

Directory Id =»TARGETDIR» Name =»SourceDir» >
Directory Id =»ProgramFilesFolder» >
Directory Id =»INSTALLLOCATION» Name =»SetupProject1″ >

—>

—>
Directory >
Directory >
Directory >

Feature Id =»ProductFeature» Title =»SetupProject1″ Level =»1″ >

—>
Feature >
Product >
Wix >

* This source code was highlighted with Source Code Highlighter .

Для начала настроим внешний вид и добавим поддержку русского языка.

Начнем с добавления русского языка. Для этого:
1. В ключе Product изменяем 1033 на 1049
2. В свойствах проекта (правой клавишей по названию проекта в Solution Explorer -> Properties), закладка Build, в поле Cultures to build вставляем ru-RU
3. Добавляем к проекту (правой клавишей по названию проекта в Solution Explorer -> Add -> Existing Item) файл WixUI_ru-ru.wxl (из архива WixUI_ru-ru.v3.zip)

В сгенерированном проекте нет ни одного диалогового окна. Существуют два варинта добавления диалоговых окон — создавать самостоятельно, либо воспользоваться готовым набором диалоговых окон.

Мы пойдем вторым путем, начинать знакомство лучше с простого. Для этого необходимо добавить ссылку на WixUIExtension.dll (правой клавишей по названию проекта в Solution Explorer -> Add Reference — открываем папку, в которую был установлен WiX, подкаталог bin)

Ссылку добавили, указываем какой набор мы будем использовать, в конце раздела Product добавим

Property Id =»WIXUI_INSTALLDIR» Value =»INSTALLLOCATION» > Property >
WixVariable Id =»WixUILicenseRtf» Overridable =»yes» Value =»License.rtf»/>
UIRef Id =»WixUI_InstallDir»/>

* This source code was highlighted with Source Code Highlighter .

WixVariable — указывает на путь к файлу лицензии (речи о нем пока не шло, добавили сразу, чтобы два раза не ходить).
WixUI_InstallDir — готовый набор диалоговых окон. Данный набор включает все необходимые нам диалоги. Помимо него так же существуют наборы WixUI_Advanced, WixUI_Mondo, WixUI_FeatureTree, WixUI_InstallDir, WixUI_Minimal.

Приготовления закончены, можно приступать к редактированию файла установки. Для начала посмотрим, что нам нагенерила студия:

Ключ Product — описывает свойства продукта.
Id — идентификатор продукта, уникальный GUID.
Name — название продукта
Language — язык пакета установки
Version — версия продукта
Manufacturer — производитель
UpgradeCode — уникальный GUID

Чтобы упростить себе жизнь определим некоторые переменные. Для чего — название продукта, например, не раз может встречаться в скрипте, если нам захочется его изменить придется искать его по всему скрипту и менять на новое. Чтобы избежать этого определим переменную, которая будет содержать название продукта и, в случае необходимости, будем менять только ее. Над разделом Product добавим:

define ProductName =»SetupProject1″ ? >
define ProductVersion =»1.0.0.0″ ? >
define ProductCode =»b7bc7c6f-9a4e-4973-be84-eca8e3427c97″ ? >
define UpgradeCode =»06a81104-1e30-463d-87e1-e8a79b4c682a» ? >
define Manufacturer =»MyCompany» ? >

* This source code was highlighted with Source Code Highlighter .

Читайте также:  Ssd windows 10 4pda

Теперь заменим значение параметров ключа Product на переменные:

Product Id =»$(var.ProductCode)» Name =»$(var.ProductName)» Language =»1049″ Version =»$(var.ProductVersion)» Manufacturer =»$(var.Manufacturer)» UpgradeCode =»$(var.UpgradeCode)» >

* This source code was highlighted with Source Code Highlighter .

Определимся теперь с тем куда мы будем устанавливать наш продукт.

Ключ Directory — определяет путь для установки.
Directory корневой элемент для всех папок, которые будут использоваться для установки проекта.
Directory папка Program Files (на что указывает
Directory папка с именем SetupProject1 в папке Program Files. Заменим сразу Name=«SetupProject1» на Name=»$(var.ProductName)»

Добавим файлы в пакет установки. Для этого сначала добавим устанавливаемые компоненты. Следуя совету «Remove the comments around this Component» уберем комментарии с Component внутри целевой папки и добавим туда, например, калькулятор.

Component Id =»ProductComponent» Guid =»b11556a2-e066-4393-af5c-9c9210187eb2″ >
File Id =’Calc’ DiskId =’1′ Source =’C:\WINDOWS\system32\calc.exe’/>
Component >

* This source code was highlighted with Source Code Highlighter .

Установка компонента невозможна без включения его в одну из Feature (если честно не уверен как в данном случае можно перевести этот термин на русский язык). Этот элемент может быть использован когда нам необходимо дать пользователю возможность выбора, что устанавливать, а что нет. В условиях нашей задачи ничего не говорилось о возможности выбора, но несмотря на это нам необходимо привязать описанный Component к одной единственной Feature:

Feature Id =»ProductFeature» Title =»$(var.ProductName)» Level =»1″ >
ComponentRef Id =»ProductComponent»/>
Feature >

* This source code was highlighted with Source Code Highlighter .

Осталось добавить ярлык в меню Пуск.

Сначала укажем, что мы собираемся работать с папкой меню Пуск и хотим там создать папку с именем нашей программы, содержащую ярлык на калькулятор.

В раздел Directory где-нибудь в конце добавляем:

Directory Id =»ProgramMenuFolder» >
Directory Id =»ApplicationProgramsFolder» Name =»$(var.ProductName)» >
Component Id =»ApplicationShortcutCalc» Guid =»4CEBD68F-E933-47f9-B02C-A4FC69FDB551″ >
Shortcut Id =»ShortcutCalc»
Name =»Calc»
Description =»$(var.ProductName)»
Target =»[INSTALLLOCATION]Calc.exe»
WorkingDirectory =»INSTALLLOCATION»/>
RemoveFolder Id =»ApplicationProgramsFolder» On =»uninstall»/>
RegistryValue Root =»HKCU» Key =»Software\$(var.Manufacturer)\$(var.ProductName)» Name =»installed» Type =»integer» Value =»1″ KeyPath =»yes»/>
Component >
Directory >
Directory >

* This source code was highlighted with Source Code Highlighter .

Начинаем разбираться:
Directory — указывает на директорию, в которой содержатся ярлыки меню Пуск.
Directory — папка нашей программы в меню Пуск
Component — компонент, содержащий ярлык (не забыть включить его в Feature)
Shortcut — собственно ярлык к калькулятору

Финальная версия файла должна выглядеть так:

Wix xmlns =»http://schemas.microsoft.com/wix/2006/wi» >
define ProductName =»SetupProject1″ ? >
define ProductVersion =»1.0.0.0″ ? >
define ProductCode =»b7bc7c6f-9a4e-4973-be84-eca8e3427c97″ ? >
define UpgradeCode =»06a81104-1e30-463d-87e1-e8a79b4c682a» ? >
define Manufacturer =»MyCompany» ? >

Product Id =»$(var.ProductCode)» Name =»$(var.ProductName)» Language =»1049″ Version =»$(var.ProductVersion)» Manufacturer =»$(var.Manufacturer)» UpgradeCode =»$(var.UpgradeCode)» >
Package InstallerVersion =»200″ Compressed =»yes»/>

Media Id =»1″ Cabinet =»media1.cab» EmbedCab =»yes»/>

Directory Id =»TARGETDIR» Name =»SourceDir» >
Directory Id =»ProgramFilesFolder» >
Directory Id =»INSTALLLOCATION» Name =»$(var.ProductName)» >
Component Id =»ProductComponent» Guid =»b11556a2-e066-4393-af5c-9c9210187eb2″ >
File Id =’Calc’ DiskId =’1′ Source =’C:\WINDOWS\system32\calc.exe’/>
Component >
Directory >
Directory >
Directory Id =»ProgramMenuFolder» >
Directory Id =»ApplicationProgramsFolder» Name =»$(var.ProductName)» >
Component Id =»ApplicationShortcutCalc» Guid =»4CEBD68F-E933-47f9-B02C-A4FC69FDB551″ >
Shortcut Id =»ShortcutCalc»
Name =»Calc»
Description =»$(var.ProductName)»
Target =»[INSTALLLOCATION]Calc.exe»
WorkingDirectory =»INSTALLLOCATION»/>
RemoveFolder Id =»ApplicationProgramsFolder» On =»uninstall»/>
RegistryValue Root =»HKCU» Key =»Software\$(var.Manufacturer)\$(var.ProductName)» Name =»installed» Type =»integer» Value =»1″ KeyPath =»yes»/>
Component >
Directory >
Directory >
Directory >

Feature Id =»ProductFeature» Title =»SetupProject1″ Level =»1″ >
ComponentRef Id =»ProductComponent»/>
ComponentRef Id =»ApplicationShortcutCalc»/>
Feature >

Property Id =»WIXUI_INSTALLDIR» Value =»INSTALLLOCATION» > Property >
WixVariable Id =»WixUILicenseRtf» Overridable =»yes» Value =»License.rtf»/>
UIRef Id =»WixUI_InstallDir»/>

* This source code was highlighted with Source Code Highlighter .

Делаем Build, запускаем, проверяем результат.

Оцените статью