Types of MSI Custom Actions

Post on 02-Jun-2015

3,620 views 0 download

Tags:

transcript

WH

ITE

PA

PE

R

Types of MSI Custom Actions

by Robert DickauPrincipal Technical Training Writer, Flexera Software

Types of MSI Custom ActionsIntroduct ionThis white paper describes some of the types of custom actions supported by Windows Installer (MSI). These types include:

•Launchingexecutables •CallingDLLorscriptfunct ions •Sett ingProperty-tablepropert iesandDirectory-

table propert ies •Erroract ions

ItalsohighlightshowInstallShield®fromFlexeraSoftwareassistsyouinworkingwithcustomact ions.

Using the InstallShield EnvironmentThis white paper frequent ly refers to the InstallShield development environment. It is assumed you are familiar withthegenerallayoutoftheInstallShieldinterface,whichcontains a list of views with which you can modify different port ions of your installat ion project.

Forexample,theGeneralInformationviewiswhereyousetgeneralproductandprojectpropert ies;theSetupDesignviewenablesyoutoeditthefeatures,components,andcomponentdatausedbyyourproject;theRegistryviewenablesyoutomodifytheregistrydatainstalledbyyourinstallat ionprogram;andtheDirectEditorviewgivesyouaccess to the raw MSI database tables.

It is also assumed you are familiar with some of the wizards availablewithInstallShield,suchastheReleaseWizardand Component Wizard.

•TheReleaseWizard,availableundertheBuildmenuandalsofromtheReleasesview,letsyoudescribethepropert ies—mediatype,compressionsett ings,andsoforth—ofarelease,andthenbuildsthespecified releaseimage.

•TheComponentWizard,availablebyright-clickingafeatureintheSetupDesignview,letsyoucreatespecialtypesofcomponents,suchascomponentsforCOMservers,fonts,andWindowsservices.

TheInstallShieldHelpLibrarycontainsinformationaboutusingeveryviewandwizardintheInstallShieldenvironment.TheInstallShieldHelpLibraryisavailablewhenyoupressF1withanyviewselected;youcanalsoselectContents from the Help menu to view the help library.

Inaddit iontothegraphicalenvironment,InstallShieldprovidesseveraltoolsformodifyingandbuildingprojectsfromthecommandlineoranexternalscript.Forexample,tobuildaprojectfromthecommandline,batchfile,orotherautomatedprocess,youcanusetheexecutableIsCmdBld.exe.TheIsCmdBldexecutableislocatedintheSystemsubdirectory of the InstallShield distribut ion directory.

Torebuildaproject,youpassIsCmdBldtheprojectfilepath,theproductconfigurat ionname,andthereleasename that you want to rebuild. A sample command appears as follows:

iscmdbld-pC:\ProductName.ism-aBuildConfig-rReleaseName

Inaddit ion,InstallShieldprovidesanAutomationinterface,withwhichyoucanmodifythecontentsofaprojectfilewithoutusingthegraphicalenvironment.

2

Types of MSI Custom Act ions

3Flexera Software: InstallShield White Paper Series

Custom Act ion BasicsThere are two steps involved for each custom act ion you want to use:

1. Define the act ion: Specify what the act ion does (launch anexecutable,callaDLLfunct ion,setaproperty,andso forth) and its other behavior (whether to test the returnvalue,andsoforth).

2. Schedule the act ion: Specify where the act ion runs relat ivetootheract ions,whichinstallat ionphase(immediateexecut ion,deferredexecut ion,andsoforth)theact ionuses,andunderwhatcondit ionsthe act ion runs.

Ageneralprincipleisthatyoushouldnotuseacustomaction when a standard act ion performs the desired task. Onereasonisthattheeffectsofcustomact ionsarenotautomatically removed when your applicat ion is uninstalled or rolled back.

Foreachcustomact ionthatperformssystemchanges,youshouldcreatecorrespondinguninstallandrollbackact ions.

Executable Custom Act ionsOneofthemostcommonlyusedtypesofcustomact ionsisanact ionthatlaunchesanexecutable.Thistypeofact ioniscommonly used to open documents installed by the current installat ion,ortolaunchsystemexecutablestoperformsystemchangesthatWindowsInstallerdoesnotdirect lysupport.Theexecutablethatyoulaunchwiththistypeofcustomact ioncanbeinstalledbythecurrentinstallat ion,alreadylocatedonthetargetsystem,orstreamedintotheBinarytableoftheMSIdatabase.

Forexample,supposeyouwanttolaunchthecopyofNotepadfromthetargetsystem’sWindowsdirectory.YoubeginbyopeningtheCustomActionsandSequencesview,right-clickingtheCustomActionsicon,andselect ing New EXE > Path referencing a directory.

In the Working Directorysett ing,enterWindowsFolder,theDirectorypropertyrepresent ingthelocationoftheexecutable.IntheFilename & Command linesett ing,entertheexecutablenamenotepad.exe.

Iftheexecutablebeinglaunchedisinadirectoryonthetargetsystem,thecustomact ionmustbeplacedafterthestandard CostFinalize act ion. The CostFinalize act ion setsthevaluesofDirectorypropert ies,andanattempttoreferenceaDirectoryproperty(suchasWindowsFolderorSystemFolder)willcauserun-t imeerror2732,whichisdescribedintheWindowsInstallerHelpLibraryas“DirectoryManagernotinit ialized”.

Inthiscase,becauseNotepad.exeispresentonthetargetsystem,thiscustomact ioncanbeplacedineithertheUserInterfacesequenceorExecutesequence(orboth),aftertheCostFinalize act ion. It is not necessary to specify deferred execut ion,orfortheInstallFilesact iontohaverunfirst.

Anexecutablecustomact iondoesnothaveaccesstoinstallat ionpropert ies,otherthanthosepassedascommand-linearguments.Atypicaluseofacommand-lineargumentistopassthepathtoadocumenttotheexecutablebeinglaunched.Forexample,supposeyouwanttolaunchaReadmefilewithNotepad.exeafterdatatransfertakesplace.Inthiscase,theFilename & Command linesett ingforthecustomact ionmightread:

notepad.exe “[INSTALLDIR]Readme.txt”

Thequotat ionmarksaroundtheargumentarerequiredbymostexecutablesincasethefilepathcontainsanyspaces.

Anact ionthatlaunchesanexecutablebeinginstalled,oronethatopensadocumentbeinginstalled,mustbescheduledfordeferredexecut ionafterthestandardInstallFilesact ion.Duringimmediatemode,datatransferhasnotyetbegun;andindeferredmodebeforeInstallFiles,documentsandexecutableswillnothavebeenplacedonthetargetsystem.

The condit ion Not Installed ensures the act ion runs—that is,theReadmefileisdisplayed—onlyduringafirst-t imeinstallat ion,andnotduringmaintenancemodeoruninstallat ion.

Toensuretheact ionrunsonlyduringafirst-t ime,full-UIinstallat ion,youcouldusethecondit ion(Not Installed) and (UILevel=5).Afurtherpossiblerefinementistoassociatetheact ionwiththecomponentcontainingtheReadmefile,usingacomponent-act ioncondit ion($ComponentName=3).

Learn More about InstallShieldIf you wish to learn more about the capabilit ies of InstallShield,pleasevisittheFlexeraSoftwareWebsite at www.flexerasoftware.com/installshield.

Types of MSI Custom Act ions

Flexera Software: InstallShield White Paper Series44

DLL and Script Custom Act ionsInadditiontorunningexecutables,WindowsInstallerenablesyoutoextendyourinstallationbycallingcodeinDLLsandscripts,wheretheDLLorscriptcanbeembeddedintheinstallation or installed with the other component data. This sectionintroducestheconceptsrelatedtocallingDLLand script code.

TheWindowsInstallerenginecandirect lycallfunct ionsfroma“WindowsInstallerDLL”,or“MSIDLL”.AnMSIDLLprovidingcustomact ionsexportsatleastonefunct ionwiththefollowingsignature:

UINT __stdcall Funct ionName(MSIHANDLE hInstall) { ... }

Afunct ionyouintendtocallfromanMSIDLLcustomact ionmustusethissignature,withtheonlyvariat ionallowedbeingthefunct ionname.Thereturnvalueisusedtodetermineifthefunct ionsucceedsorfails,andthereforewhethertheinstallat ionshouldexitasaresultofthecustomact ion;andtheMSIHANDLEargumentpassedtothefunct ionisahandletotherunninginstallat ion,usedasanargumenttoMSIAPIfunct ionssuchasMsiGetPropertythatquerytherunninginstallat ion.

WindowsInstallerrequiresthataDLLusedinthistypeofcustomact ionmustbeacallableDLL,andnotaVisualBasicDLLor.NETDLL.TheDLLfunct ioncannotacceptarguments,butinsteadmustpassinformationbackandforthusingWindowsInstallerpropert ies.TheMsiSetPropertyfunct ionsetsthevalueofaproperty,andMsiGetPropertyreadsthevalue of a property.

NOTE: The InstallShield environment supports a special type ofDLLcustomact ioncalleda“StandardDLL”act ion,whichenablesyoutocallDLLfunct ionswithsignaturesdifferentfromtheMSIDLLfunct ionpresentedearlier.WhenyoucreateaStandardDLLcustomact ion,youwillbepromptedfortheDLLname,thefunct ionname,andforconstantsorpropert iesusedtoprovidethefunct ionargumentsandreturnvalues.RecentInstallShieldversionsalsosupport“managedcode”customact ions,suchasC#andVB.NETDLLmethods.

CodeforasimpleMSIDLLcustomact ionmightappear as follows:

#pragmacomment(lib,“msi.lib”)#include<windows.h>#include<msi.h>#include<msiquery.h>// an MSI DLL custom act ion funct ion must use this signatureUINT__stdcallCustomActionFunct ion(MSIHANDLEhInstall){MessageBox(GetForegroundWindow(),TEXT(“RunningMSIDLLact ion...”),TEXT(“MSIDLL”),MB_OK|MB_ICONINFORMATION);

returnERROR_SUCCESS;// return success to MSI}AssumingthiscodehasbeencompiledintoaDLLcalledMsiDllCustomAction.dll,andthatthefunct ionnameCustomActionFunct ioniscorrect lyexportedfromtheDLL(usinga.deffile,forexample),thepropert iesofacustomact ionthatcallstheDLLmightappearsimilartothefollowingfigure.IntheFunct ion Namesett ing,youspecifyonly the funct ion name because the return value and argumentsarepredefinedforanMSIDLL.

Similarly,aVBScriptcustomact iontypicallydefinesafunct ionsimilartothefollowing:

Funct ion Funct ionName( ) ‘ do something End Funct ion

Theexceptionisthesett ingVBScript > Stored in custom act ion,whichcanstoreshortscriptsdirect lyintheCustomActiontable,andforwhichyoudonotspecifyafunct ion name.

LikeMSIDLLcustomact ionfunct ions,VBScriptcustomact ionfunct ionsdonotacceptarguments,butinsteadmustalsocommunicatewiththerunninginstallerengineusingpropert ies.InVBScriptcustomact ions,theSessionobjectrepresentstherunninginstallat ion,andtheexpressionSession.Property(“PROPNAME”)enablesyoutogetandsetthe value of a property.

Sett ing Propert iesAset-a-propertycustomact ioneithersetsorcreatesaproperty.IfthepropertyexistsinthePropertytable,thecustomact ionwilloverwriteitsvalue,andifthepropertydoesnotexistinthePropertytable,thecustomact ionwillcreateit.Asdescribedpreviously,however,thevaluesofprivatepropert iesareresettotheirdefaultswhenexecut ionswitchesfromtheUserInterfacesequencetothe Executesequence.

Anadvantagetousingset-a-propertycustomact ionsoverdefiningpropert iesinthePropertytableisthattheact ioncanresolveFormattedexpressions,whileentriesinthePropertytabledonotresolveFormattedexpressions.Forexample,youcancreateacustomact ionthatsetsTIMESTAMPtothevalue“[Date]at[Time]”,andthevaluesoftheembeddedpropert iesDateandTimewillbeexpandedatrunt ime.YoucanthenusetheFormattedexpression[TIMESTAMP]in,forexample,aregistryvalue,andthevaluewillbeexpandedatrunt ime.

Types of MSI Custom Act ions

5Flexera Software: InstallShield White Paper Series

Anexampleofthistypeofcustomact ionthatexistsineachnewInstallShieldprojectiscalledSetARPINSTALLLOCATION,whichsetsthepredefinedpropertyARPINSTALLLOCATIONto[INSTALLDIR].ThevalueofARPINSTALLLOCATIONisautomaticallywrittentothetargetsystem’sregistrybytheWindowsInstallerengine,enablingacustomact ionorexternalprogramtoreadthemaininstalldirectoryforanexist ingproductusingtheMsiGetProductInfofunct ionorInstaller.ProductInfomethod.Becausepropert iescannotbesetduringdeferredexecut ion,theIn-ScriptExecut ionsett ingforaset-a-propertycustomact ioncannotbechangedfromImmediateExecut ion.

Sett ing Directory Propert iesYoucanalsouseset-a-directorycustomact ionstosetthevaluesofDirectorypropert ies.Directorypropert iesare those that refer to the locations of directories on the targetsystem;built-inexamplesareProgramFilesFolder,DesktopFolder,andSystemFolder.IfyouwanttomodifythelocationthataDirectorypropertypointsto,youcanusea set-a-directoryact ion.

Directorypropert iesaresetbythedisk-cost ingprocess,andthereforeset-a-directorycustomact ionsmustbescheduledafter the standard CostFinalize act ion.

NOTE: Windows Installer ensures that the value of each Directorypropertyendswithabackslash.IfyourinstallerwritesaDirectorypropertytotheregistryusingtheformat[INSTALLDIR],forexample,atypicalvalueisC:\Program Files\Our Company\Our Applicat ion\. If the value is to be readlaterfromwithinyourapplicat ion,yourapplicat ioncodemustaccountforthetrailingbackslash.

Forexample,supposeyouhaveacomponentthatyouwantto install to a directory located by a custom act ion. In this case,assumethecustomact ionpopulatesapropertycalledFOUND_DIR.Oneoptionistodefinethecomponenttouseacustompropertywithanarbitraryinit ialvalue,andthenuseaset-a-directorycustomact iontosettheplaceholderpropertyvalueto[FOUND_DIR].

Inthefollowingfigure,acomponenthasbeengivenadest inat iondirectoryrepresentedbytheDirectorypropertynameSETTINGS_DIR,withadefaultvalueof[ProgramFilesFolder]Sett ings.

To install this component to the directory located by the customact ion,createaset-a-directorycustomact ionwithsourceSETTINGS_DIRandtarget[FOUND_DIR],schedulingtheact ionaftertheCostFinalizeact ioninboththeUserInterfaceandExecutesequences.

(Notethattheact ionusesthecondit ionFOUND_DIR,whichensuresSETTINGS_DIRischangedfromitsdefaultvalue only if custom act ion found the desired directory.)

Atinstallat iont ime,thecomponent’sfileswillbeinstalledtothe directory discovered by the custom act ion.

Error Custom Act ionsErrorcustomact ionsdisplayanerrormessagetotheenduser,andthenexittheinstallat ionwhentheuserdismissestheerrordialog.Becauseanerrorcustomact ionalwaysexitstheinstallat ion,youshouldattachacondit iontoanerror act ion to ensure it runs only when appropriate.

When you create an error act ion in the Custom Actions andSequencesview,youcanusetheErrorMessagesett ingtospecifytheerrormessagethatshouldbedisplayedwhentheact ion’scondit ionsaremetatrunt ime.Supposethat you schedule the act ion immediately after the LaunchCondit ionsact ionintheExecutesequence.Whenyourebuildandruntheproject,theeffectofthecustomact ionistodisplayanerrordialogboxsimilartothefollowing:

Aftertheenduserdismissestheerrordialogbox,theinstallat ionexits.(Forasilentinstallat ion,theerrormessageisbydefaultwrittentoanMSIlogfile,andalsotothesystem’sapplicat ioneventlog.)

TheErrorMessagesett ingforanerrorcustomact ionusestheFormatteddatatype,soyoucanexpandthevaluesofpropert iesusingthesyntax[PropertyName].

Types of MSI Custom Act ions

Flexera Software: InstallShield White Paper Series6

Inaddit ion,theErrorMessagesett ingforanerrorcustom act ion can contain the number of a record in the Errortable.TheErrortableisalsoexposedintheDirectEditorview.AsdescribedintheWindowsInstallerHelpLibrarytopic“ErrorTable”,theerrorcodesnumberedfrom25000to30000arereservedforcustomact ions,andthereforeyoucanusenumbersinthisrangeforyourcustommessages.TheadvantagetousinganentryintheErrortable,insteadofusingahard-codedmessageintheErrorMessagesett ing,isthatError-tablemessagesareautomaticallyaddedtotheInstallShieldstringtable,andthereforeyoucanprovidelocalizederrormessagesformult i-languageinstallat ions.

IntheDirectEditorview,youcreatearecordintheErrortablethesamewayyoudoforanyothertable.ThefieldsusedintheErrortablearetheErrorfield,whichmustbeanintegererrornumber,andtheMessagefield,containingthemessagetodisplay.WhenyouaddarecordtotheErrortable,theInstallShieldenvironmentautomaticallyaddsanentrytothestringtable;foreachlanguageyourprojectsupports,youeditthestringvalueintheStringTablesview,availableinsideyourproject’sGeneralInformationview.

Foranexampleofusinganerrorcustomact ion,supposeyouhavecreatedamajorupgradeofanexist ingproject,and want to allow the installat ion to cont inue only if an earlierproductversionisdetected.Youcandetectifamajorupgradeistakingplacebytest ingifthe“act ionproperty”definedinanUpgrade-tablerecordcontainsanyvalue.

First,youcreatetheerroract ionintheCustomActionsandSequencesview.Youcanschedulethecustomact ioninboththeUserInterfaceandExecutesequencesaftertheFindRelatedProductsact ionwithcondit ionNotISACTIONPROP1.Theact ion’spropert iesmightbe as follows:

Next,usetheDirectEditorviewtocreatethemessageintheErrortable:

Error: 29000Message: Youmusthaveapreviousversionof[ProductName]installed.Setupwillnowexit.

Whenyouruntheinstallat ion,becausenoearlierversionoftheproductisdetected,thefollowingerrormessage is displayed.

SummaryThis white paper discusses some of the types of custom act ions supported by Windows Installer (MSI). It also highlightshowInstallShieldfromFlexeraSoftwareassistsyouinworkingwithcustomact ions.

How Flexera Software Professional Services Can HelpAsthemainmechanismforincreasingfunct ionalityofyourMSI,soundknowledgeoftheworkingsofMSIcustomact ionsiscrucial.LetFlexeraSoftware’sexpertsguideyouthroughthevariousoptions.Findoutmoreatwww.flexerasoftware.com/services/consulting/software-installations.htm.

Begin a Free Evaluation of InstallShieldYoucandownloadafreetrialversionofInstallShieldfromtheFlexeraSoftwareWebsiteat: www.flexerasoftware.com/installshield/eval

Want to learn more best pract ices for building quality installat ions?JoinanInstallShieldtrainingclass–visitwww.flexerasoftware.com/training for available classes.

Types of MSI Custom Act ions

7Flexera Software: InstallShield White Paper Series

About Flexera SoftwareFlexeraSoftwareistheleadingproviderofstrategicsolut ionsforApplicat ionUsageManagement;solut ionsdeliveringcont inuouscompliance,optimizedusageandmaximizedvaluetoapplicat ionproducersandtheircustomers.FlexeraSoftwareistrustedbymorethan80,000customersthatdependonourcomprehensivesolut ions-from installat ion and licensing,ent it lementandcompliancemanagement to applicat ion readiness and enterprise license optimization-tostrategicallymanageapplicat ionusageandachievebreakthroughresultsrealizedonlythroughthesystems-levelapproachweprovide.Formoreinformation,pleasegoto:www.flexerasoftware.com

WH

ITE

PA

PE

R

Flexera Software LLC1000 East Woodfield Road, Suite 400Schaumburg, IL 60173 USA

Schaumburg (Global Headquarters):+1 800-809-5659

United Kingdom (Europe, Middle East Headquarters):+44 870-871-1111+44 870-873-6300

Japan (Asia, Pacific Headquarters):+81 3-4360-8291

For more office locat ions visit:www.flexerasoftware.com

Copyright © 2011 Flexera Software LLC. All other brand and product names ment ioned herein may be the trademarks and registered trademarks of their respect ive owners. IS_WP_MSIAct ionTypes_Oct11