Read installer version from an .ini file stored in the same directory in Inno Setup - inno-setup

I want to distribute the compiled installer with a separate INI file. The setup will load configurations (e.g. a version) from an INI file supplied to that particular client.
I have a ver.ini file in the same directory as the Setup.exe. It contains-
[Version]
Ver=0.0.11
I want to use it like-
#define AppVer ReadIni("ver.ini", "Version", "Ver", "unknown")
The Problem: Inno Setup is showing AppVer as unknown, rather than 0.0.11.
If I use a hard-coded file path for the ver.ini file, it works:
#define AppVer ReadIni("C:\Users\Admin\Desktop\ver.ini", "Version", "Ver", "unknown")
Since I'm distributing the Setup to my customers, I cannot use a hard-coded file path.
Any help is appreciated!

You cannot use a preprocessor. The preprocessor is executed on compile time. So even if you fix the path problem (e.g. using SourcePath preprocessor variable), it won't help, as you will be reading INI file on the machine that compiles your installer. Not on the machine, where the installer is executed.
You have to use Pascal Scripting and a scripted constant. Use GetIniString function to read the INI file and src constant to refer to the source directory.
[Setup]
AppVersion={code:GetAppVersion}
[Code]
function GetAppVersion(Param: string): string;
var
IniPath: string;
begin
IniPath := ExpandConstant('{src}\ver.ini');
Result := GetIniString('Version', 'Ver', 'Unknown', IniPath);
end;
You may want to abort the installation in case the version cannot be found:
function GetAppVersion(Param: string): string;
var
IniPath: string;
begin
IniPath := ExpandConstant('{src}\ver.ini');
Result := GetIniString('Version', 'Ver', '', IniPath);
if Result = '' then RaiseException('Cannot find version');
end;

Related

How can I rewrite predefined messages for the WelcomePage in different languages in Inno Setup?

I have 3 languages and I need to change the AppName according to the language I've chosen.
I wrote this:
[Setup]
AppName={code:GetMyAppName}
[Code]
function GetMyAppName(param : String) : String;
begin
case ActiveLanguage of
'en': Result := 'AB Office Client';
'ru': Result := 'Клиент АБ Офис';
'ua': Result := 'Клієнт АБ Офіс';
end;
end;
And here I have my language-dependent [Messages] section:
[Messages]
en.WelcomeLabel1=Welcome to [APPNAME] Setup program. This program will install [APPNAME] on your computer.
ru.WelcomeLabel1=Вас приветствует программа установки [APPNAME] Эта программа установит [APPNAME] на Ваш компьютер.
ua.WelcomeLabel1=Вас вітає програма встановлення [APPNAME]. Ця програма встановить [APPNAME] на Ваш комп'ютер.
My question is: how can I transfer the result of the function GetMyAppName to the [APPNAME]? I could have done that by inserting a previously defined constant like {#AppName}, but I cannot use functions from the [Code] section with preprocessor's directives.
The same question is when I use [CustomeMessages] instead. Like this:
[Setup]
AppName={cm:AppName}
[CustomMessages]
en.AppName=AB Office Client
ru.AppName=Клиент АБ Офис
ua.AppName=Клієнт АБ Офіс
Also, I know that there are some arguments %1 and %2 in [Messages] section, but i have no idea how to use them. For me %1 and %2 argument just won't transfer to the AppName and AppVersion accordingly. They just stay as %1 and %2.
And finally, changing the .isl file manually is not an option for me.
Would really appreciate your help. Have a nice day.
The defaults are:
WelcomeLabel1=Welcome to the [name] Setup Wizard
WelcomeLabel2=This will install [name/ver] on your computer.%n%nIt is recommended that you close all other applications before continuing.
So just follow that – Use [name] and [name/ver] placeholders in your translations.
If you need other customization, see Can I use .isl files for the messages with preprocessor directives in Inno Setup? or Full preprocessor support in Inno Setup language files (isl).

How to reference the files in the Files section from Code/Pascal section?

In my code section I need to modify an existing configuration file (Apache httpd.conf) to include one of the files I'm installing in the Files section.
How can I reference my .conf file, so I can insert into the httpd.conf something like this:
Include "C:/Program Files (x86)/Apache Software Foundation/Apache2.4/conf/myinclude.conf"
I think I can do something like:
ExtractFilePath( {app} ) + '\conf\myinclude.conf'
to get the full path of the file.
However that means I have to hard code the partial path in my script code. If we later change the path then I have to change it in the files section and remember to change it in the script code too.
Is there a way to reference the file just by name and get the full installed path?
Secondary question:
What's the best place to do this kind of thing (modifying a file)?
In the AfterInstall of the file I'm going to modify it for?
In NextButtonClick on wpFinished?
Other?
Use a preprocessor constant/variable.
The best place to update the httpd.conf is CurStepChanged(ssPostInstall). The AfterInstall will do too.
#define MyIncludeName "myinclude.conf"
#define MyIncludeRelPath "conf\" + MyIncludeName
[Files]
Source: "{#MyIncludeName}"; DestDir: "{app}\..\{#MyIncludeRelPath}"
[Code]
procedure CurStepChanged(CurStep: TSetupStep);
var
Path: string;
begin
if CurStep = ssPostInstall then
begin
Path := ExtractFilePath(ExpandConstant('{app}')) + '{#MyIncludeRelPath}';
...
end;
end;

Inno Setup: Can the installer update itself?

My installer creates a folder with my app and the installer itself. The installer is later on used as an updater for the application.
All of this works well but I would like to update the installer itself and not just my application.
I download a zip from my server and expect everything inside the zip to override everything in the app folder (including the installer itself).
Every time I run the installer I get an error that a file is already in use.
Can the installer update itself?
You cannot replace running application.
You have these options:
Start the "updater" via batch file (referring to assumed shortcut to the updater in a Start menu or any other method of invocation), that makes a copy of the installer to a temporary location and runs the updater from there. When updating, update the original copy.
To avoid the batch file (and an unpleasant console window), you can use JScript. Or even make the installer (updater) do this itself (create a copy of itself, launch the copy, exit itself).
Use restartreplace flag in Files section entry to schedule installer/updater replace for the next Windows start.
Keeping the installer in the {app} directory is probably acceptable for small applications, for larger ones consider an updater, or even another location, (in the form of a feature request) {Backup} to refer to a path on some flash or removable drive.
Run the setup from the {app} directory and after the version check, download the installer to the {tmp} folder.
Exec the installer thus before quitting, keeping mind of possible mutex conditions in the code section of your script:
if Exec(ExpandConstant('{tmp}\{OutputBaseFilename}), '', '', SW_SHOW,
ewNoWait, ResultCode) then
// success/fail code follows
To copy the installer back to {app} the Install script will have this in Files:
[Files]
Source: "{srcexe}"; DestDir: "{app}"; Flags: external
Presumably the above line will not produce an error when the installer is actually run from {app}.
Then, to clean up, the next time the installer is run from the {src} (= {app}) directory, the downloaded one can be removed from the {tmp} directory with
DeleteFile({tmp}\{OutputBaseFilename})
I've run into this same problem recently. We have a main installer that manages a bunch of other setup packages for our applications, and I wanted to add some mechanism for this main installer to update itself.
I've managed to find a solution creating a second Inno Setup package that serves just as an updater for the main installer, and that updater goes embedded in the main installer.
So, we have a XML file in our website that gives the latest version available for the main installer:
[ InstallerLastVersion.xml ]
<?xml version="1.0" encoding="utf-8"?>
<installer name="Our Central Installer" file="OurInstaller.exe" version="1.0.0.1" date="10/15/2021" />
The main code for this auto-update functionality in the main installer is that:
[ OurInstaller.iss ]
[Files]
; This file won't be installed ('dontcopy' flag), it is just embedded
; into the installer to be extracted and executed in case it's necessary
; to update the Installer.
Source: ".\OurInstallerUpdater.exe"; Flags: dontcopy
[Code]
const
UrlRoot = 'http://ourwebsite.com/';
// Downloads a XML file from a website and loads it into XmlDoc parameter.
function LoadXml(XmlFile: String; var XmlDoc: Variant): Boolean;
begin
XmlDoc := CreateOleObject('MSXML2.DOMDocument');
XmlDoc.async := False;
Result := XmlDoc.Load(UrlRoot + XmlFile);
end;
// Checks if there's a newer version of the Installer
// and fires the updater if necessary.
function InstallerWillBeUpdated(): Boolean;
var
XmlDoc: Variant;
LastVersion, Filename, Param: String;
ResultCode: Integer;
begin
if not LoadXml('InstallerLastVersion.xml', XmlDoc) then
begin
Result := False;
Exit;
end;
// Gets the latest version number, retrieved from
// the XML file download from the website.
LastVersion := XmlDoc.documentElement.getAttribute('version');
// If this installer version is the same as the one available
// at the website, there's no need to update it.
if '{#SetupSetting("AppVersion")}' = LastVersion then
begin
Result := False;
Exit;
end;
if MsgBox('There is an update for this installer.' + #13#10 +
'Do you allow this installer to be updated right now?',
mbConfirmation, MB_YESNO) = IDNO then
begin
Result := False;
Exit;
end;
// Extracts the updater, that was embedded into this installer,
// to a temporary folder ({tmp}).
ExtractTemporaryFile('OurInstallerUpdater.exe');
// Gets the full path for the extracted updater in the temp folder.
Filename := ExpandConstant('{tmp}\OurInstallerUpdater.exe');
// The current folder where the installer is stored is going to be
// passed as a parameter to the updater, so it can save the new version
// of the installer in this same folder.
Param := ExpandConstant('/Path={src}');
// Executes the updater, with a command-line like this:
// OurInstallerUpdater.exe /Path=C:\InstallerPath
Result := Exec(Filename, Param, '', SW_SHOW, ewNoWait, ResultCode);
end;
function InitializeSetup(): Boolean;
begin
// Checks if the installer needs to be updated and fires the update.
// If the update is fired the installer must be ended, so it can be
// replaced with the new version. Returning this InitializeSetup()
// function with False already makes the installer to be closed.
if InstallerWillBeUpdated() then
begin
Result := False;
Exit;
end;
Result := True;
end;
Now to the updater code (I'm using the "new" DownloadTemporaryFile() function added in Inno Setup 6.1):
[ OurInstallerUpdater.iss ]
[Code]
const
UrlRoot = 'http://ourwebsite.com/';
Installer = 'OurInstaller.exe';
function InitializeSetup(): Boolean;
var
DestinationPath: String;
ResultCode: Integer;
begin
// Retrieves the parameter passed in the execution
// of this installer, for example:
// OurInstallerUpdater.exe /Path=C:\InstallerPath
// If no parameter was passed it uses 'C:\InstallerPath' as default.
// (where {sd} is the constant that represents the System Drive)
DestinationPath := ExpandConstant('{param:Path|{sd}\InstallerPath}') + '\' + Installer;
try
// Downloads the newer version of the installer to {tmp} folder.
DownloadTemporaryFile(UrlRoot + Installer, Installer, '', nil);
// Copies the downloaded file from the temp folder to the folder where
// the current installer is stored, the one that fired this updater.
FileCopy(ExpandConstant('{tmp}\') + Installer, DestinationPath, False);
// Runs the updated installer.
Exec(DestinationPath, '', '', SW_SHOW, ewNoWait, ResultCode);
except
MsgBox('The file ''' + Installer + ''' could not be downloaded.', mbInformation, MB_OK);
end;
// Returning False from this function implies that this
// updater can now be finished, since its goal has already
// been reached (to update the main installer).
Result := False;
end;
In this setting you have to build OurInstallerUpdater.exe before OurInstaller.exe, since the first one is embedded into the second one.
Some sources:
Inno Setup: Install file from Internet
Using {AppVersion} as a parameter for a function in Inno Setup
Exit from Inno Setup installation from [Code]
Is it possible to accept custom command line parameters with Inno Setup
How to get the installer path in Inno Setup?

Inno setup search for existing file

How can I search for an existing exe file and then use that directory for my installer ?
If the exe file is not found I would like the user to browse for the path. In case the exe file is installed somewhere else.
Senario 1 (most common cases):
Default dir is c:\test\My program
This should be shown as the path on the "Select Destination Location" page
When the user press Next, there should be a check. To make sure that the default dir exist (c:\test\My program)
If it exist, the user should just continue to the Ready to Install page.
Senario 2 (very seldom cases):
Default dir is c:\test\My program
This should be shown as the path on the "Select Destination Location" page
When the user press Next, there should be a check. To make sure that the default dir exist (c:\test\My program)
If it does not exist, the user should be prompt for the path to "My program". The user should afterwards continue to the Ready to Install page.
I then just trust that the user selects the correct path
How can I do this in InnoSetup ?
I do a similar thing with my installer already. The first thing I do is need to read the registry value from the program, and if that registry value is absent then I select that program's default directory. For example:
DefaultDirName={reg:HKLM\Software\Activision\Battlezone II,STInstallDir|reg:HKLM\Software\Activision\Battlezone II,Install121Dir|{pf32}\Battlezone II}
Now, the user runs the installer, and it has to check if the program is in the right folder. It does so by checking that the program's executable file already exists. I use this piece of code to do so.
{ Below code warns end user if he tries to install into a folder that does not contain bzone.exe. Useful if user tries to install into addon or any non-BZ2 folder. }
function NextButtonClick(CurPageID: Integer): Boolean;
begin
Log('NextButtonClick(' + IntToStr(CurPageID) + ') called');
case CurPageID of
wpSelectDir:
if not FileExists(ExpandConstant('{app}\bzone.exe')) then begin
MsgBox('Setup has detected that that this is not the main program folder of a Battlezone II install, and the created shortcuts to launch {#MyAppName} will not work.' #13#13 'You should probably go back and browse for a valid Battlezone II folder (and not any subfolders like addon).', mbError, MB_OK);
end;
wpReady:
end;
Result := True;
end;
The above code simply checks that the target executable exists and warns the user if it does not, giving him the chance to go back and change directories but also to go ahead with the install anyways.
Also, as you appear to be installing a patch or addon to an existing program, I recommend you set
DirExistsWarning=no
AppendDefaultDirName=false
And optionally to prevent an unnecessary screen if you are not creating start menu entries
DisableProgramGroupPage=yes
I would make a file input page and let user choose the Picture.exe binary location manually, when it won't be found on expected location.
You can follow the commented version of this code:
[Setup]
AppName=My Program
AppVersion=1.5
DefaultDirName={pf}\My Program
OutputDir=userdocs:Inno Setup Examples Output
[Files]
Source: "CurrentBinary.exe"; DestDir: "{app}"
Source: "PictureExtension.dll"; DestDir: "{code:GetDirPath}"
[Code]
var
FilePage: TInputFileWizardPage;
function GetDirPath(const Value: string): string;
begin
Result := '';
if FileExists(FilePage.Values[0]) then
Result := ExtractFilePath(FilePage.Values[0]);
end;
procedure InitializeWizard;
var
FilePath: string;
begin
FilePage := CreateInputFilePage(wpSelectDir, 'Select Picture.exe location',
'Where is Picture.exe installed ?', 'Select where Picture.exe is located, ' +
'then click Next.');
FilePage.Add('Location of Picture.exe:', 'Picture project executable|Picture.exe',
'.exe');
FilePage.Edits[0].ReadOnly := True;
FilePage.Edits[0].Color := clBtnFace;
FilePath := ExpandConstant('{pf}\Picture\Picture.exe');
if FileExists(FilePath) then
FilePage.Values[0] := FilePath;
end;

How to get Inno Setup to unzip a file it installed (all as part of the one installation process)

To save bandwidth/space as well as prevent accidental meddling, the installation files for a database product (call it Ajax), have been zipped up (call that file "AJAX_Install_Files.ZIP). I would like to have Inno-Setup "install" (i.e., copy) the AJAX_Install_Files.ZIP file to the destination, and then Unzip the files into the same folder where the .ZIP file is located. A subsequent program would be fired off by Inno Setup to actually run the install of product "Ajax".
I've looked through the documentation, FAQ, and KB at the Inno Setup website, and this does not seem possible other than writing a Pascal script (code) - would that be correct, or are there are any alternative solutions?
You can use an external command line tool for unzipping your archive, see here for example. Put it in your [Files] section:
[Files]
Source: "UNZIP.EXE"; DestDir: "{tmp}"; Flags: deleteafterinstall
Then call it in your [Run] section, like this:
[Run]
Filename: "{tmp}\UNZIP.EXE"; Parameters: "{tmp}\ZipFile.ZIP -d C:\TargetDir"
(You'll probably want to take your target directory from a script variable, so there is some more work that needs to be done)
You can use the shell Folder.CopyHere method to extract a ZIP.
const
SHCONTCH_NOPROGRESSBOX = 4;
SHCONTCH_RESPONDYESTOALL = 16;
procedure UnZip(ZipPath, TargetPath: string);
var
Shell: Variant;
ZipFile: Variant;
TargetFolder: Variant;
begin
Shell := CreateOleObject('Shell.Application');
ZipFile := Shell.NameSpace(ZipPath);
if VarIsClear(ZipFile) then
RaiseException(
Format('ZIP file "%s" does not exist or cannot be opened', [ZipPath]));
TargetFolder := Shell.NameSpace(TargetPath);
if VarIsClear(TargetFolder) then
RaiseException(Format('Target path "%s" does not exist', [TargetPath]));
TargetFolder.CopyHere(
ZipFile.Items, SHCONTCH_NOPROGRESSBOX or SHCONTCH_RESPONDYESTOALL);
end;
Note that the flags SHCONTCH_NOPROGRESSBOX and SHCONTCH_RESPONDYESTOALL work on Windows Vista and newer.
For an example of extracting some files only, see:
How to get Inno Setup to unzip a single file?
I answered a very similar question and some of the details apply.
I would question why you need a ZIP file of the contents? I personally would place the uncompressed files into the setup. I would then have two [category] entries one for the application and one for the data. Default both the be checked.
This would allow the users to install a fresh set of the data if needed at a later date.
If you really want a ZIP file and want to keep it easy you could, ship both the zip files and the uncompressed files in the same setup.
Update:
By default files that get placed in your setup.exe are compressed.
You can also have the files extracted to a temporary location so you can run your
installation application, then have them deleted.
[Files]
Source: "Install1.SQL"; DestDir: "{tmp}"; Flags:deleteafterinstall;
Source: "Install2.SQL"; DestDir: "{tmp}"; Flags:deleteafterinstall;
You can just create silent self-extracting archive (SFX) archive, example described here how to create SFX archive for stuff you need, and write Pascal code to just run it like this (script for Inno Setup 6.0.2):
[Tasks]
Name: "intallSenselockDriver"; Description: "Install Senselock driver."; GroupDescription: "Install the necessary software:";
[Code]
function ExecTmpFile(FileName: String): Boolean;
var
ResultCode: Integer;
begin
if not Exec(ExpandConstant('{tmp}\' + FileName), '', '', SW_SHOWNORMAL, ewWaitUntilTerminated, ResultCode)
then
begin
MsgBox('Other installer failed to run!' + #13#10 + SysErrorMessage(ResultCode), mbError, MB_OK);
Result := False;
end
else
Result := True;
end;
procedure RunOtherInstallerSFX(ArchiveName: String; ExePath: String);
begin
ExtractTemporaryFile(ArchiveName);
ExecTmpFile(ArchiveName);
ExecTmpFile(ExePath);
end;
function PrepareToInstall(var NeedsRestart: Boolean): String;
begin
if WizardIsTaskSelected('intallSenselockDriver') then
RunOtherInstallerSFX('1_senselock_windows_3.1.0.0.exe', '1_senselock_windows_3.1.0.0\InstWiz3.exe');
Result := '';
end;
It worked perfectly for me.
Using Double quotes worked for me.
Single quotes were not working.
[Files]
Source: "unzip.exe"; DestDir: "{userappdata}\{#MyAppName}\{#InputFolderName}"; Flags: ignoreversion
[Run]
Filename: "{userappdata}\{#MyAppName}\{#InputFolderName}\unzip.exe"; Parameters: " ""{userappdata}\{#MyAppName}\{#InputFolderName}\ZIPFILENAME.zip"" -d ""{userappdata}\{#MyAppName}\{#InputFolderName}"" "; Flags: runascurrentuser

Resources