Tải bản đầy đủ (.pdf) (456 trang)

Apress the definitive guide to windows installer apr 2004 ISBN 1590592972

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (4.14 MB, 456 trang )

TheDefinitiveGuidetoWindowsInstaller
ISBN:1590592972
byPhilWilson
Apress©2004(302pages)
Thisguidedemonstrateshowtobuildsafeand
secureinstallations,aswellasbuildexample
projectsasVisualStudioSetupand
DeploymentProjects.Itwillshowyouhowyou
needtodesignapplicationstointegrate
properlywithWindowsInstaller.
TableofContents
TheDefinitiveGuidetoWindowsInstaller
Introduction
Chapter1 - InstallationsPast,Present,andFuture
BuildinganMsiFile:VisualStudioand
Chapter2 Orca
Chapter3 - COMintheWindowsInstallerWorld
Chapter4 - SearchesandConditions
Chapter5 - SequencesofEventsandCustomActions
Chapter6 - HowdoYouFixIt?
Chapter7 - ASP.NETSetups
Chapter8 - Installing.NETAssemblies
Chapter9 - InstallationDesign
Chapter10 - WindowsServices
Chapter11 - TheGacandUpdatingAssemblies
Chapter12 - UpdatesusingPatches
Chapter13 - InstallationEnvironments
Chapter14 - How-Tos,Tips,andGotchas


Chapter15 - ExploringtheInstallerAPIs


Chapter16 - ToolsandFutures
Index
ListofFigures


BackCover
Whenacompanybuildsandshipssoftware,the
installationprocessisoftenthefirstopportunityfora
customertoviewtheproductandthecompany—and
theinstallationexperiencecanmakeorbreakalasting
impression.Sothisbookisidealforcompaniesand
developerswhowanttoimpresstheirclientele.
ThisbookcoverseveryaspectofusingtheWindows
Installer—theunderlyinginstallertechnologyin
Windows.Avaluabletoolforyousoftwaredevelopers,
thisbookhelpsensurethoroughandreliable
installationforyourcustomers.Mostotherbooksfor
softwaredevelopersendtooabruptlyandomitcritical
information,likehowtocreatethenecessary
installationsoftware.ButTheDefinitiveGuideto
WindowsInstallerpicksupwheretheotherbookstrail
off.
AbouttheAuthor
PhilWilsongraduatedfromtheUniversityofAston,
Birmingham,England,withabachelor'sdegreein
chemistry,buthepreferredcomputerstotesttubes
andeventuallyworkedfor15yearsondeveloping
operatingsystemsforBurroughsandUnisys
mainframes.PhilstartedprogrammingforWindowsin
theearly1990sandhasdevelopedinMFC,ATLCOM,

VisualBasic,andC#.Hehasbeeninvolvedin
installationdesignandtechnologyforabout8years,
andhebecameaMicrosoftMVPforWindowsInstaller
in2003.Togetawayfromcomputers,heplaysand


recordsguitar,andenjoyscampingintheCalifornia
desert.


TheDefinitiveGuidetoWindowsInstaller
PHILWILSON

Copyright©2004byPhilWilson
Allrightsreserved.Nopartofthisworkmaybereproducedortransmitted
inanyformorbyanymeans,electronicormechanical,including
photocopying,recording,orbyanyinformationstorageorretrieval
system,withoutthepriorwrittenpermissionofthecopyrightownerand
thepublisher.
ISBN(pbk):1-59059-297-2
PrintedandboundintheUnitedStatesofAmerica10987654321
Trademarkednamesmayappearinthisbook.Ratherthanusea
trademarksymbolwitheveryoccurrenceofatrademarkedname,weuse
thenamesonlyinaneditorialfashionandtothebenefitofthetrademark
owner,withnointentionofinfringementofthetrademark.
LeadEditor:DanAppleman
TechnicalReviewers:ChrisGouge,CarolynNapier
EditorialBoard:SteveAnglin,DanAppleman,GaryCornell,James
Cox,TonyDavis,JohnFranklin,JasonGilmore,ChrisMills,Steve
Rycroft,DominicShakeshaft,JimSumser,KarenWatterson,GavinWray,

JohnZukowski
ProjectManager:TracyBrownCollins
CopyManager:NicoleLeClerc
CopyEditor:SusannahPfalzer
ProductionManager:KariBrooks
Compositor:VijayNicoleImprints


Proofreader:LizWelch
Indexer:CarolBurbo
CoverDesigner:KurtKrames
ManufacturingManager:TomDebolski
DistributedtothebooktradeintheUnitedStatesbySpringer-VerlagNew
York,Inc.,175FifthAvenue,NewYork,NY10010andoutsidetheUnited
StatesbySpringer-VerlagGmbH&Co.KG,Tiergartenstr.17,69112
Heidelberg,Germany.
IntheUnitedStates:phone1-800-SPRINGER,e-mail
<>,orvisit.OutsidetheUnitedStates:fax+496221345229,e-mail
<>,orvisit.
Forinformationontranslations,pleasecontactApressdirectlyat2560
NinthStreet,Suite219,Berkeley,CA94710.Phone510-549-5930,fax
510-549-5939,e-mail<>,orvisit
.
Theinformationinthisbookisdistributedonan"asis"basis,without
warranty.Althougheveryprecautionhasbeentakeninthepreparationof
thiswork,neithertheauthor(s)norApressshallhaveanyliabilitytoany
personorentitywithrespecttoanylossordamagecausedorallegedto
becauseddirectlyorindirectlybytheinformationcontainedinthiswork.
Thesourcecodeforthisbookisavailabletoreadersat
intheDownloadssection.

AbouttheAuthor
PhilWilsongraduatedfromtheUniversityofAston,Birmingham,
England,withaBScinchemistry,butpreferredcomputerstotesttubes
andeventuallyworkedfor15yearsondevelopingoperatingsystemsfor
BurroughsandUnisysmainframes.Philstartedprogrammingfor
Windowsintheearly1990sandhasdevelopedinMFC,ATL,COM,


VisualBasic,andC#.Hehasbeeninvolvedininstallationdesignand
technologyforabouteightyears,andbecameaMicrosoftMostValuable
ProfessionalforWindowsInstallerin2003.Togetawayfromcomputers,
heplaysandrecordsguitar,andenjoyscampingintheCaliforniadesert.
PhilworksforUnisysCorporationinMissionViejo,California.
Acknowledgments
ManythankstothepeopleatApressforgivingmethisopportunity,
especiallyDanAppleman.ThankstoTracyBrownCollins,Susannah
Pfalzer,andKariBrooksforgettingmethroughitall.Alotprobablygoes
oninthisprocessthattheykeptmeblissfullyunawareof;allIhadtodo
waskeepwriting.
MyheartfeltthanksgotoChrisGougeandCarolynNapierofMicrosoft
fortheirtechnicalreview.Theypatientlycorrectedmymisunderstandings,
andthebookismuchbetterfortheirreview.Ican'timaginewhatitmust
feelliketohavesomeonewriteabookaboutthesoftwarethatyouwork
oneveryday,sotothemandtherestoftheWindowInstallerteam:I
hopeI'vedoneagoodjob.
ThanksalsotoR.MichaelSanfordforhisearlyreviewwork.
Finally,thankstomyfamilyfortheirpatiencewhileIwasholedup
eveningsandweekendsfortheduration,andthankstomyfriendsM.G.,
A.K.,andV.R.forbelievinginme.



Introduction
Installingnewsoftwareisperhapsthemostadrenalin-inducing
experienceyou'llhaveonacomputer,asidefromwhatevergamesyou
mightplay.It'snothardtoseewhy.Yougiveovercontrolofthesystemto
aprogramthatoftendemandsAdministratorprivilegeandthatthenstarts
updatingsomeofthemostfragilepartsofyoursystem.Youmightknow
theactualproductbeinginstalledquitewell,butthere'srarelyany
documentationaboutwhattheinstallationofitwilldotoyoursystem.It
mightinstallkerneldriversorServices,itmightalteryourpersonal
settingswithoutyourpermission,anditmightresultinotherapplications
onyoursystemnolongerworking.Foracompanybuildingandshipping
software,theinstallationmightbethefirsttimethecustomerhasseen
yourproductoryourcompany,andit'syouropportunitytomakealasting
impressiononewayortheother.Anunreliableinstallationwillaffectthe
customer'simageofyouforalongtime.
Thegoalofthisbookistoshowyouhowtobuildsafeandsecure
installations.ItsfocusisWindowsInstallertechnologyontheWindows
NTseriesofoperatingsystemsforWindows2000andabove,andyou'll
buildexampleprojectsasVisualStudioSetupandDeploymentProjects.
AsidefromtheactualnutsandboltsofbuildingWindowsInstaller-based
installations,I'llofferadviceonhowtobuildareliableinstallationand
whatyoushouldandshouldn'tdo.Theintegrationofinstallertechnology
aspartoftheWindowsoperatingsystemmeansthatthedividingline
betweenanapplicationanditsinstallationhasbecomemuchlesssharp,
andthebookwillcoverhowyouneedtodesignapplicationstointegrate
properlywithWindowsInstaller.
Thebookstartswithbasicprinciplesanddrillsdowndeeperinlater
chapters.Istartwiththeinstallationequivalentofthe"HelloWorld"
program,andthengraduallygetdeeperintothecontentsofinstallerMSI

files,includinginstallationinthe.NETFrameworkworld.AlongthewayI'll
stoptolookatbestpracticesandhowtokeepyourinstallationreliable.
WhereIshowuseoftheinstallerAPIs,I'lluseVBScriptforthesakeof
simplicityandclarity,butI'llalsopointyouattheWin32equivalentsand
showyouacoupleofwaystocallthemfromthe.NETFramework


languageC#.
Asisoftenthecasewhenyoutrytoexplainsomething,youfindthatyou
testyourunderstanding,andifyou'reluckyyoulearnsomethingnewat
thesametime.IhopeyoulearnasmuchfromreadingthisbookasIdid
writingit.


Chapter1:InstallationsPast,Present,and
Future
Itoftenseemsthattheinstallationofaproductisalmostanafterthought.
Developersspendhundredsoflabor-monthsbuildingthatgreatnew
three-tierapplication.However,Iwouldn'tbesurprisedifyou'rereading
thisbookbecauseyou'rethepersonwhohastofigureouthowtoinstall
theapplicationwhileeveryoneelseisoutcelebratingthefactthatthey've
finishedit.Ofcourse,anapplicationisn'tactuallyfinisheduntilyoucan
installitonyourclients'systems.


Background
Manypeopleseeinstallationsasasimpleprocessofcopyingfilestothe
clientsystem,butinreality,copyingfilesisprobablythemost
straightforwardpartofthewholeinstallationprocess.Wheninstallinga
productontheWindowsoperatingsystem(OS),youneedtoconsiderall

thefollowingareas,andthisisnotacompletelistbyanymeans.

WheretheFilesGo
Itisnotalwaysobviouswherefilesshouldactuallybeinstalled.Theusual
conventionisthattheygetcopiedtotheProgramFilesfolderassociated
withyourcompanynameandproductname.Butthisisn'talwaysthe
case.Forexample,ifyourcompanyhasasetofcomponentobjectmodel
(COM)components,thenyoucan'tusuallyhaveyourownprivatecopyin
eachoftheproduct'sfolders.ThereisonlyonesetofCOMregistration
entriesonthesystem.Ifyouinstallthecomponentatonelocationinone
product,thenatanotherlocationfromanotherproduct,thelastcopyof
thecomponentistheonethatalltheclientprogramswilluse.That's
becausetheinstallmarkstheInprocServer32entrytopointtothelast
locationthesharedcomponentwasinstalledto.Uninstallinganyoneof
theproductsbreaksalltheremainingproductsbecausetheuninstall
removestheregistrationdatawhentheprogramisuninstalled.

RedistributingSupportingFiles
Manyproductsalsoneedsupportingsoftwaretobeinstalledbeforethey
willfunctioncorrectly.Sometimesthismeansacollectionofsupporting
DLLsorOCXs,sometimesitmeanssomethingrathercomplicatedsuch
astheMicrosoftDatabaseEngine(MSDE)software.Notonlythat,but
differentoperatingsystemshavedifferentrequirements.Toshowa
coupleofexamples,Windows2000hasmanyoftheVisualStudio6.0
supportDLLsforVisualBasic,ATL,andMFCprojectsaspartofthe
operatingsystem,sotheydon'tneedtobeinstalled.However,ifyou're
supportingWindowsNT4.0,theydo.Microsoft'sVisualStudio.NET


(VS.NET)hasanewsetofredistributables(ATL70.DLL,MFC70.DLL,

MSVCR70.DLL)thatalwaysneedinstalling,evenonWindows2000.This
areacanbeconfusingandcontributestothegeneralexpressionforthis
situation—"DLLHell."

InstallingWindowsServices
WindowsServicessometimesdependonotherServicesthatarealready
onthesystem.InstallingaServicemightthereforerequirestoppingthese
otherServices,installingyours,thenstartinguptheseotherServices,
andfinallystartingyourService.

FilesinUse
Thetypicalproblemwithin-usefilesisthatyou'retryingtoreplacethem
withnewerversions.Itisgoodpracticetoattempttoshutdownthe
applicationusingthesefiles.IftheapplicationisaServiceoran
applicationthathasauserinterface,youmightbeabletosend
messagestocloseitdown(orprompttheusertodoso),butsomeof
thesescenarioscanbecomplex.YoumightbetryingtoregisteraCOM
DLLbycallingitsDllRegisterServerfunction(whichiswhat
REGSVR32.EXEdoes).However,thatDLLmightrequireadependent
DLLthatcouldnotbeinstalledbecauseanolderversionofthat
dependentDLLisinuse.Inthesesituationstheonlyrecourseisto
arrangeareboottogetthefilesreplaced.InthecaseofregisteringCOM
servers,youtypicallyneedtowriteanentrytothesystemRegistry's
RunOncekeytoregistertheDLL,andthenarrangethereboot.

SecurityandtheTargetUser
InstallationsoftenhavetoberunwithAdministratoraccountprivileges
becausetheyupdatepartsofthesystemthatrequireprivilegestocreate
ormodifythem.Ontheotherhand,sayyou'reinstallingonashared
computerandyou'dliketoinstallsomethingonbehalfofanotheruser.

AlthoughyoucouldgoaheadandinstallitwithanAdministrator's
account,it'snotclearthatyouwantthisotherusertohaveAdministrator
privileges.Thereisalsoaprivacyissueonsharedcomputers,perhaps


notsomuchwhenoneindividualinstallssomethingforanother,butinthe
corporateworldwhereseveralusersmightbesharingonecomputer.
Therefore,thereisoftenaconflictbetweenthesecurityrequirementsof
theinstallationandthesecurityrequirementsoftheinstalledproduct.

MaintainingtheProduct
It'saprettysafeassumptionthatsoonerorlateraproductwillneed
updates,whethertheyarebugfixesorfeatureadditions.Youneeda
mechanismthatcanidentifywheretheexistingfilesarelocatedonthe
clientsystemandreplacethemwithnewversions.Thismaintenance
requirementhasallthedrawbacksyoualreadylookedatrelatingtofiles
inuseandsoon,withtheadditionaldifficultiesofworkingoutwhattodo
iftheupdatefails.Thiscanmeanidentifyingthefilesthataretobe
updated,andbackingthemupsomewhere.Thatwaytheusercan
restorethemiftheupdatefailsoriftheuserfindsthattheupdated
productisbrokenandneedstouninstalltheupdate.Thisisthemodel
usedwithWindowsServicePacks.Becauseofthesepossible
requirements,thistypeofservicepackinstallationissometimesdifferent
thantheoriginalinstallation,andyoumayuseadifferenttooltobuildit.It
wouldnotbeunusualforaninstallationdevelopertoneedtounderstand
atleasttwotypesofinstallation—theoriginalproductinstallationandthe
toolsthatbuildit,plusthetoolstobuildservicepacks.

Environments
Forexample,ifaproductconsistsofthreedistincttiers,therearelikelyto

bethreedistinctenvironmentsontowhichyouhavetoinstallsomepiece
oftheapplication.Perhapsyouneedtodividetheproductintoseparate
features,oneperenvironment.Perhapsfilesorprogramsarecommonto
someofthetiers,soyouwouldneedtobreakoutthesecommonfiles
intosomekindofseparatefeature(notvisibletotheuser)thatcanbe
installedonallthetiersbydefault.Eachtiermightalsobeadifferenttype
ofWindowsenvironment.Forexample,theback-endtiermightrequirea
serveroperatingsystem,soyouprobablydon'twanttoallowittobe
installedonaworkstation.Inotherwords,theapplicationneedstobe
brokenupintopiecesandrebuiltasasetoffeaturesthatcanbetargeted


attheappropriateuserorplatform.

TheOne-WayNatureofInstallations
Althoughyouusuallycallaninstallationprograma"program,"it'snotlike
otherprogramsinacoupleofinterestingways.Ifyouhaveanapplication
programthathasabug,youshipafixtoyourclients,whoreplacetheold
versionwiththenewoneandstartrunningthenewversion.Installation
programsaren'tlikethat.Ifyou'veshippedabrokeninstallation,youcan't
justshipacorrectedonetoyourclientsandaskthemtouseit.That's
becausenoprogramontheclient'ssystemcanbereplaced—it'snot
literallyaprograminthatsense.Inreality,aninstallationisaprocess,a
sequenceofactionsthatalterthetargetsystem,andoncetheinstallation
hasdoneitsworkyoucan'tjustreplaceitwithacorrected(updated)
version.Thereisalsotheuninstallprocesstokeepinmind.Oncethe
producthasbeeninstalled,thensohastheuninstallprocess,soit's
essentialthattheuninstallprocessworkproperly.Aproductthatcannot
beuninstalledispotentiallyuselessiffixingorreplacingitrequiresusers
touninstallit.


DevelopmentEaseandtheInstallation
Developmenttoolsmakeiteasytobuildprograms.Youuseawizard,
addsomecode,andyoursystemisalreadysetupwiththesupport
necessaryforyoutotesttheprogram.I'mexaggeratingsomewhat,but
thepointisthatwhenyouinstalltheprogramorapplicationonaclient
system,youneedtoknowabouteachfile,supportingDLL,andRegistry
entrythattheapplicationneedsforittorun.Ifyou'recommunicatingthis
tosomeonewho'sbuildingtheinstallationprogram,detailingeverything
that'sneededisanontrivialtask.

DevelopmentInstallsvs.ProductionInstalls
Developmentenvironmentsanddocumentationfrequentlytalkintermsof
command-lineprogramsthatperforminstallationtasks.InCOM,
developersareusedtotheideaofrunningRegsvr32.exetoregisterCOM
DLLs,ora–Regservercommand-lineargumenttoregisteraCOMlocal


server.Inthe.NETFrameworkworldyouseereferencestorunning
Regasm.exe,Gacutil.exe,andInstallutil.exetoinstallassembliesfor
.NETCOMInterop,toinstallassembliesintotheGlobalAssemblyCache
(theGAC),ortoregisterassembliesas.NETWindowsServices.
However,notoneofthesecommand-lineprogramsisnecessaryfora
WindowsInstaller–basedinstallationbecauseinstallersupportis
providedforthefunctionalityofferedbytheseprograms.


IntroducingWindowsInstaller
BeforeWindowsInstallertherewasnospecificWindowsfunctionality
suppliedtoinstallproducts.(Strictlyspeaking,therehasalwaysbeenthe

SetupAPI,butitsmainfunctionalityisbasedonusingINFfilesto
performinstallations.)TheWindowsprogrammingenvironment
happenedtoberichenoughthatdeveloperscoulduseitsAPIsto
performinstalls.Amajorconsequenceofusingthegeneral-purpose
WindowsAPIswasthattherewasnoconsistentintegrationbetween
Windowsandtheinstalledproduct.Forexample,ifyouwantedto
inventorytheproductsinstalledonasystem,youcouldenumeratethe
contentsoftheRegistryareausedbytheAdd/RemoveProgramsapplet,
butanynumberofdifferenttoolscouldhaveinstalledeachproduct,and
evenasimpletasksuchasfindingwheretheproductwasinstalledwas
nontrivial.
AroundtheWindows2000timeframe,MicrosoftsuppliedWindows
InstallerastheinstallationtechnologyforMicrosoftOffice2000.I'lltakea
brieflookhereattheproblemsithelpssolve,andamorein-depthlookin
laterchapters.WindowsInstallerprovidesastandardwaytoinstall,
maintain,anduninstallsoftware.However,thatbyitselfisnotjustification,
solet'slookatwhatmakesWindowsInstalleruniqueandhowit
addressessomeoftheprecedingtopics.

TransactionalBehavior
Nobodywantsaninstallationtogetpartiallycompletedandthenfailfor
somereason,leavingasysteminsomeindeterminatestate.Windows
Installerturnsproductinstallationsintoanall-or-nothingproposition—the
productiseithersuccessfullyinstalledonthesystem,ortheinstallation
doesnotworkandallthechangesthatmighthavebeenmadetothe
systemarebackedout.
Alargepartofthistransactionalnatureisaconsequenceofeliminating
asmuchcodeaspossiblefromtheinstallationprocess.Asyou'llsee
later,WindowsInstalleroffersfeaturesthatmeanyoudon'tnecessarily
needtoruncustomcodeatinstalltime.Thisisnecessarybecause



otherwiseyou,theinstallationdeveloper,wouldberesponsiblefor
reversinganychangesmadetothesystemduringtheinstallation.
Asanexample,considerCOMserverregistration.AsInotedearlier,a
COMserverhistoricallyrequireditsDllRegisterServerfunctiontobe
called,andlikewisetheuninstallprocesswouldcallDllUnregisterServer.
ThisrequirestheCOMservertoinitialize,whereitmightneeda
dependentDLLthatisn'tonthesystemyet.WindowsInstallerdealswith
thisbystoringCOMregistrationdatainsidetheactualinstallerpackage,
theMSIfile,soitdoesn'tneedtocallorruntheCOMservertoinstallor
uninstalltheRegistryentries.WindowsInstallercanaddorremovethe
COMRegistryentrieswhethertheCOMserveritselfisfunctionalornot.
InstallingtheCOMservermeanscopyingthefiletothesystemand
writingtheRegistryentriesfrominstallertables.
ThesamegeneralideaappliestoWindowsServices(sometimescalled
NTServices).Whentheyareinstalledwithsomethinglikea–Service
command-lineargumenttoarunoftheServiceprogramitself,installand
uninstallaredependentontheServicebeingfunctional.However,
WindowsInstallerhassupportforinstallingServicesdirectlyfromthe
installationpackagewithnorequirementtoruntheServiceexecutableto
installit.Consequently,installationandremovaloftheServiceare
controlledmoresafely.

Repair
It'snotunusualforfilesthatbelongtoaproducttogetaccidentally
deleted.WindowsInstallerhasrepairfeaturesthatrestoreanapplication
thatisbrokenbecauseofmissingfilesorRegistryentries.Ifthe
installationmarksafileoraRegistryentryas"key,"WindowsInstaller
hasthecapabilitytorestorethefileorentryautomaticallyifit'smissing.

WhenyougotoAdd/RemovePrograms,aRepairchoiceisoffered,
alongwithotherchoicestouninstallormodifytheinstalledfeatures.
Repairisprobablythefeaturethatmostoftensurprisesdevelopers.They
aregenerallyfamiliarwiththeideathataproductcanbeinstalledand
thenmanipulatedafterwardsbyaddingnewfilesorremovingunwanted
ones,onlytofindthattherepairmechanismrestoresthefilesorRegistry


keystotheinitialinstallationstate.Userstooaresometimessurprised
whentheyremoveashortcutandmoveittosomeotherlocation,onlyto
findthatWindowsInstallerrestoresitthrougharepair.

64-bit
ThereissupportinWindowsInstallerforinstallingapplicationsonto64bitWindowsoperatingsystems.Thisdoesn'tjustmeanthatyoucan
install32-bitapplicationsonto64-bitsystems,itmeansthatWindows
Installerislikelytobetheonlywaytoinstall64-bitapplicationsontoa64bitsystem.

SharingFiles
Sharinghasalwaysbeenanimportantaspectofinstallations.The
sharingissuesarelargelyresponsibleforthesituationpopularly(or
unpopularly)knownas"DLLHell."YouneedtoworkoutwhichMicrosoft
DLLsneedinstallingtosupportyourproduct,andconsequentlyrunthe
riskofcreatinganincompatiblesetofsystemDLLs.Oryoumighthave
sharedcomponentsinyourcompany'sproductsthatallneedtobe
installedandmanagedcorrectlyonclientsystems.Thisisbecomingless
ofanissuesinceWindows2000introducedWindowsProtectedFiles,a
featurethatpreventsinstallationsfromreplacingcriticalsystemfiles.
WindowsInstallerdoesnotevenattempttoreplacethoseprotectedfiles
thatareconsideredtobepartoftheOS.
SharinginWindowsInstallerusesreferencecountsforeachunique

component.Youstillneedtofollowrules,asyou'llseelater,butthe
WindowsInstallercomponentsharingmechanismismuchmorerobust
thanpreviousschemes.

SystemIntegration
ProductsinstalledwithWindowsInstallerareintegratedintoWindows.
APIsandCOMobjectscanreportinformationaboutinstalledproductsto
adetailedlevel.Inaddition,aWindowsManagementInstrumentation
(WMI)providerreportsthecontentandconfigurationofinstalled


products.Ifyoueverwonderedwhetherthereisawaytodiscover
accuratelywhatproductsareinstalledonasystem,thefactthatthereare
standardAPIcallsisavastimprovementcomparedtoprowlingthe
Registrylookingforproducts.TheseAPIsnotonlyreturndetailabout
potentiallyeveryfileinstalledbyaproduct,theyalsoallowtheapplication
codeitselftointegratewiththeinstallationandmodifyinstalled
componentsonthefly.TheAPIsalsoallowaccesstoinstallation
packages(MSIfiles).Forexample,it'srelativelyeasytoquerythe
contentsofaninstallationpackageandcomparethecontentswitha
versionofthatpackagethatisinstalledonthesystem.

.NET
WindowsInstallerhasbuilt-insupportforinstalling.NETassembliesinto
theGlobalAssemblyCache(GAC).Thisislikelytobetheonlywayyou
shouldinstallassembliesintotheGAC.Yes,Microsoftsuppliesthe
Gacutil.exeutilityinthedevelopmentenvironment,butthisprogram
knowsnothingabouttheWindowsInstallerreference-countingscheme,
sosharedassembliesinstalledintotheGACrequireWindowsInstallerto
maintaincorrectshared-installerreferencecounts.


FortheSystemorforCurrentUser
Whenyoustartinstallingaproductyouareoftenaskedifit'sbeing
installedforyou(privatetoyouraccountonthesystem),orwhetherit's
beinginstalledforeveryone.Thesegenerallyaffectwhether,forexample,
certainRegistryentriesarewrittentotheHKEY_CURRENT_USER
(HKCUarea)ortoHKEY_LOCAL_MACHINE(HKLM).Ifyouassumethat
thetargetuserisinfactthecurrentuserofthesystem,thismeansthat
theapplicationshouldnotbevisibletootherusers.Butthinkaboutthe
mechanicsofCOMregistration,wherecodeintheDllRegisterServer
entrypointcreatesCOMregistrationentriesonthesystem.You'llrealize
thatthereisnowaythatthecodeinDllRegisterServerknowswhetherthe
installationisper-userorper-machine,sotheregistrationcodecannot
knowwhichRegistrylocationisthecorrectone,HKLMorHKCU.The
codeinDllRegisterServerregisterstothelocalmachineRegistrykeys,so
ineffectaninstallforthecurrentuserleavesCOMserversaccessibleto


everyoneonthesystem.ItthereforemakesalotofsensetogetCOM
serversoutofthebusinessofself-registrationandhaveWindows
InstallercreatetheregistrationentriesintheappropriateRegistry
location.

SecurityofInstallationvs.SecurityofProduct
Whentryingtoinstallaproductforauserwhomightnothavethe
securityprivilegestoinstalltheproduct,thereneedstobeawayforthis
usertoinstalltheproductwithoutrequiringthoseelevatedprivilegesona
permanentbasis.WindowsInstallerprovidessomewaystodealwith
theseissues.Onereasonithelpswiththeseissuesisbecauseitrunsas
aWindowsServiceanddoesn'tneedtobeconstrainedbytheprivileges

ofthecurrentuser.Anotherreasonisbecausepoliciescanbeconfigured
soyoucanperformaninstallationwithelevatedprivilegesonbehalfofa
userwhoisnotprivileged.

UpdatingandDeployingNewVersions
BeforeWindowsInstaller,whenyouwantedtoshipcorrectionstoa
product,perhapsyousimplyrebuilttheentireinstallationsetupandsent
ittoyourclients.However,youcan'tjustaskyourclienttoinstallthe
product,becauseyou'dendupwithtwocopiesoftheproductonthe
system.However,ifyou'resupplyingafixoranupdateyouneedto
replacetheexistinginstalledproduct.Generallyspeaking,theincoming
newinstallationwoulddetecttheexistingoneanduninstallit,orperhaps
evenarrangetocompletelyinstallitselfontopoftheexistingproduct.
Anotherchoicewouldbetoproduceaservicepacktoupdatethe
product,oftenrequiringuseofaseparatetooltoinstalltheupdatestothe
clientsystem.Tosummarize,therehavebeenanumberofwaystodeal
withthesemaintenanceissues.WindowsInstallerhassomeformal
mechanismsforinstallingproductupdatesandfixes.

Advertisement
Youcanthinkofadvertisementasinstallation-on-demand.Itcanbe
particularlyusefulincorporateenvironments—youcanhavepractically


everythinginstalled(shortcuts,Registryentries,andsoon)exceptforthe
files.Whenyoureferencetheadvertisedproduct,theinstallationstarts
installingthefilesfromanetworklocationontotheclientsystem.Even
afteraproducthasbeeninstalled,perhapssomeofitsfeatureswillbe
advertised,sothatwhentheadvertisedfeatureisfirstusedthisfeatureis
installed.

Theideaofadvertisedfeaturesisthatyouinstallahookofsomekind,
typicallyashortcut.Usingthisshortcutcausesthefeaturetobeinstalled.
IftheadvertisedfeatureconsistsofoneormoreCOMcomponents,there
isasimilaradvertisementinstallationstepthatcausesthecomponentto
beinstalled.

RunningYourOwnCode
Manyoftheobservationsmadeinthischaptermightgivetheimpression
thatyoucan'taddyourowncodetotheinstallationprocess.Infactyou
can—whenyoudothisit'scalledacustomaction.Manytypesofcustom
actionsallowyoutorunVBScript,executables,andcallintoaDLL,to
quoteafewexamples.Sothatchangestothesystemcanbeprovided
withtransactionalbehaviorinmind,youcanassociatethesecustom
actionswiththeinstall,theuninstall,andalsotherollbackprocessthat
occurswhenaninstallationfailsandeverythingdonetothesystemis
beingundonetorestorethesystemtoitsoriginalstate.


TheTools
WindowsInstallerpackageshavetheMSIfileextension,andthe
WindowsInstallerServiceinstallsthesepackages.YoucanuseanSDK
here,justlikeinmanyotheraspectsofWindowsprogramming.Inthis
case,youusetheWindowsInstallerSDK,whichispartofthePlatform
SDK.Thiscontainsdocumentation,tools,andsamplecodetocreateand
modifyinstallerpackages.VS.NETofferswizardsandadevelopment
environmenttobuildinstallationpackages.
Third-partyvendorswhoprovidetoolstocreateinstallationsetupshave
beenaroundforawhile(forexample,InstallShieldSoftware).These
companies'toolshistoricallyhavebuiltinstallationpackagesthatdiffer
fromoneanother,althoughmostgenerateawizard-basedapproachto

theinstallationprocess.Theinnerworkingsoftheinstall—thecode,the
logfilesandsoon—areallproprietary.
AfterMicrosoftintroducedtheWindowsInstallerService,thesevendors
introducedtoolstocreateinstallerpackages(MSIfiles).Apartfrom
companiesandproductssuchasInstallShield,Wise,OnDemand
Software'sWinINSTALL,ZeroGSoftware'sInstallAnywhere.NET
(formerlyActiveInstall),andCornerHouseSoftware,thereareopen
sourceandfreetoolsthatyoucanusetobuildinstallerpackages.
AlthoughthisbookusesVS.NETextensivelyforitssamples,itis
importanttorealizethatVisualStudioDeploymentProjectsprovidejusta
basicauthoringtoolforcreatingpackagescomparedtosomeofthemore
advancedthird-partyproducts.It'squitelikelythatyouoryourcompany
willwanttobuildinstallerpackagesusingfeaturesthatWindowsInstaller
providesbutthatarebeyondthecapabilitiesofVisualStudioDeployment
Projects.Althoughthisbookwillhelpyoubuildanduseinstaller
packages,you'llfinditmucheasiertobuildmorecomplexinstallation
packagesusingafullyfeaturedtoolwithsupportforyourrequired
functionalitybuiltintoitsIntegratedDevelopmentEnvironment(IDE).
EverythingyoulearninthisbookaboutWindowsInstallerwillbeuseful
nomatterwhichtoolyoueventuallydecidetouse,butyou'llfindthatthe
rightdevelopmenttoolmakestheprocessofbuildinginstallerpackages
easierandfaster.


Summary
Perhapsthemostimportantcharacteristicofaninstallationpackage
(installerterminologyforanMSIfile)isthatitisadatabase.Thisisnot
looseterminology;itreallyisadatabasewithtablesorganizedinto
columnsandrows.Asyou'llseelater,youcanevenuseSQL-like
statementstoqueryorupdatetheinstallationpackage.Thetablesinthe

packagedescribethefiles,features,shortcuts,Registryentries,COM
classes,andyourcustomactioncode,tonamesomeofthecontent.
Eventheorderinwhichactivitiesoccurduringtheinstallationprocessis
determinedbytablesthatcontaineachactionanditsorderrelativeto
otheractions.
Asyou'llseeasyouprogressthroughthefollowingchapters,Windows
Installersuppliesaframeworkforinstallations.Likemostframeworks,it
worksbestwhenyoudon'tbendit.Whenyoudesignanddevelop
applications,you'realmostcertainlyawareofthelimitationsand
capabilitiesoftheimplementationyou'regoingtouse,andyoutakethese
intoaccountwhenyoudesigntheapplication.Thesameistrueof
WindowsInstaller.Ifyoucometodesignaproductinstallation,youmust
beawareofthedirectionthatthetechnologywouldpreferyoutotake.It's
probablynoexaggerationtosaythatmostinstallationproblemsarethe
resultofapreconceiveddesignorimplementationplanthatdoesn'tfitthe
framework.
You'llseehowalltheseexamplesworkusingactualexamplesof
installationpackages,solet'sgetgoingandbuildyourfirstinstallation
package.


Chapter2:BuildinganMsiFile:VisualStudio
andOrca
Inthischapter,you'llbuildaninstallerpackageusingaVS.NETSetup
andDeploymentProjectandlookatitwithatoolcalledOrca,partofthe
WindowsInstallerSDK.


Background
First,somehistoryandanoverviewofVS'scapabilitiesintheinstallation

area.
MicrosofthasoftenaddedcapabilitiesforbuildinginstallationsinVS—
perhapsyou'veusedtheVisualBasicPackageandDeploymentWizard.
Ifyou'veusedVS6.0,youmighthaveusedthefirstversionofVisual
StudioInstaller,whichwasavailableasafreedownloadforVSlicensees.
VS.NETisthefirstreleaseofVSthatintegratestheabilitytobuild
WindowsInstallerpackageswiththeIDE.However,VS.NET'sinstallation
toolcomeswithsomelimitationsandrestrictionsthatbecomeapparent
asyouuseit.Thisdoesn'tmeanthatMicrosoftdidabadjob,butitdoes
meanthatifyouwanttouseasubstantialsetofWindowsInstaller's
features,youshouldlookbeyondVS.NET'sinstallertool.LookinChapter
16foralistofsomeofthevendorsthatsupplyfullyfeaturedtoolsto
createinstallerpackages.
OneofthetoolsthatMicrosoftsuppliestoviewandmodifyinstaller
packagesiscalledOrca.YoucanfinditintheWindowsInstallersection
ofthePlatformSDK;theinstallationpackageis(whatelse?)aninstaller
packagecalledORCA.MSI.Afteryou'veinstalledit,you'llfindthatthe
right-clickcontextmenuonWindowsInstallerfiles(notablypackages,
MSIfilesandmergemodules,MSMfiles)allowsyoutoopenandedit
them.You'llbeusingOrcalatertoviewandmodifyinstallationpackages.
I'lldescribeeverythingIcoverhereregardingWindowsInstallerconcepts
inmoredetailinlaterchapters.Inthischapter,you'llbuildaninstaller
packagesothatyoucanlookinsidetheactualMSIfile;that'swhenyou'll
useOrca.


×