Foros Club Delphi

Foros Club Delphi (https://www.clubdelphi.com/foros/index.php)
-   Varios (https://www.clubdelphi.com/foros/forumdisplay.php?f=11)
-   -   Evitar que mi app se instale en un equipo con mi app instalada (InnoSetup) (https://www.clubdelphi.com/foros/showthread.php?t=87270)

diegoferxmr 05-12-2014 17:06:57

Evitar que mi app se instale en un equipo con mi app instalada (InnoSetup)
 
Hola a todos.

Me gustaria por favor que me ayudaran con ésta situación:
Quiero que el instalador de mi aplicación se cancele si se está ejecutando en un equipo que tiene ya mi aplicación instalada.
Yo busco un archivo clave que siempre se instala con mi app, y con éste código no me funciona:

Código Delphi [-]

begin
Log( 'InitializeSetup' );
// Default.
//
Result := true;

if FileExists('{app}\carpeta1\mi_archivo.xla') then
begin
MsgBox('Mi aplicación ya está instalada, la instalación se cancelará', mbCriticalError, MB_OK);
Result := False;
Exit;
end

En otro foro muestran éste código, pero no se como acoplarlo:

Código Delphi [-]
function FileDoesNotExist(file: string): Boolean;
begin
if (FileExists(file)) then
begin
Result := False;
end
else
begin
Result := True;
end;
end;

Agradezco mucho su ayuda!

Ñuño Martínez 07-12-2014 14:38:54

Si no recuerdo mal, InnoSetup por sí sólo ya detecta si la aplicación está instalada o no. ¿O me he perdido algo?

dec 07-12-2014 14:54:13

Hola,

Cita:

Empezado por Ñuño Martínez (Mensaje 486221)
Si no recuerdo mal, InnoSetup por sí sólo ya detecta si la aplicación está instalada o no. ¿O me he perdido algo?

Creo que hay alguna opción para detectar si la aplicación está ejecutándose (de manera que el instalador te sugiere cerrarla antes de seguir) pero no para saber si la aplicación está instalada. De todas formas igual sí que hay manera de saberlo, puesto que no conozco bien todas y cada una de las opciones de Inno Setup, pero son muchísimas.

Por lo demás, en el código Pascal de arriba se usa una constante de Inno Setup: "{app}", pero, no puede usarse tal como se hace, sino que es menester usar cierta función "ExpandConstant" para convertir dicha constante en su valor correspondiente. Es decir, jhabría que hacer algo similar a esto:

Código Delphi [-]

var
  MyAppPath: string;

begin
  Log( 'InitializeSetup' );
  // Default.
  //
  Result := true;

  MyAppPath := ExpandConstant('{app}');

  if FileExists(MyAppPath + 'mi_archivo.xla') then 
  begin
    MsgBox('Mi aplicación ya está instalada, la instalación se cancelará', mbCriticalError, MB_OK);
    Result := False;
    Exit;
end

diegoferxmr 09-12-2014 18:04:58

Cita:

Empezado por dec (Mensaje 486224)
Hola,



Creo que hay alguna opción para detectar si la aplicación está ejecutándose (de manera que el instalador te sugiere cerrarla antes de seguir) pero no para saber si la aplicación está instalada. De todas formas igual sí que hay manera de saberlo, puesto que no conozco bien todas y cada una de las opciones de Inno Setup, pero son muchísimas.

Por lo demás, en el código Pascal de arriba se usa una constante de Inno Setup: "{app}", pero, no puede usarse tal como se hace, sino que es menester usar cierta función "ExpandConstant" para convertir dicha constante en su valor correspondiente. Es decir, jhabría que hacer algo similar a esto:

Código Delphi [-]

var
  MyAppPath: string;

begin
  Log( 'InitializeSetup' );
  // Default.
  //
  Result := true;

  MyAppPath := ExpandConstant('{app}');

  if FileExists(MyAppPath + 'mi_archivo.xla') then 
  begin
    MsgBox('Mi aplicación ya está instalada, la instalación se cancelará', mbCriticalError, MB_OK);
    Result := False;
    Exit;
end

Hola.
Mil gracias por responder.
He compilado el código, sin embargo me sale el siguiente error:

Line 82,
column 3,
Uknown identifier: 'Result'

¿Quizás podría modificar el código así?:

Código Delphi [-]

var
  MyAppPath: string;

begin
  Log( 'InitializeSetup' );
  // Default.
  //
  MyAppPath := ExpandConstant('{app}');

  if FileExists(MyAppPath + 'mi_archivo.xla') then 
  begin
    MsgBox('Mi aplicación ya está instalada, la instalación se cancelará', mbCriticalError, MB_OK);
    Result := False;
    Exit;
else
    Result := true;
end

¿o así?:

Código Delphi [-]

var
  MyAppPath: string;

begin
  Log( 'InitializeSetup' );
  // Default.
  //
  MyAppPath := ExpandConstant('{app}');

  if FileExists(MyAppPath + 'mi_archivo.xla') then 
  begin
    MsgBox('Mi aplicación ya está instalada, la instalación se cancelará', mbCriticalError, MB_OK);
    Result := False;
    Exit;
  end
  begin
else
    Result := true;
end
end

Mil gracias para todo el que conteste.
Un saludo. :)

nlsgarcia 09-12-2014 22:08:48

diegoferxmr,

Cita:

Empezado por diegoferxmr
...que el instalador de mi aplicación se cancele si se está ejecutando en un equipo que tiene ya mi aplicación instalada...busco un archivo clave que siempre se instala con mi app...

:rolleyes:

Revisa este código:
Código Delphi [-]
// Script generated by the Inno Setup Script Wizard.
// SEE THE DOCUMENTATION FOR DETAILS ON CREATING INNO SETUP SCRIPT FILES!

#define MyAppName "Setup OOP"
#define MyAppVersion "1.0"
#define MyAppPublisher "Nelson, C.A."
#define MyAppURL "http://www.clubdelphi.com"
#define MyAppExeName "OOP.exe"

[Setup]
// NOTE: The value of AppId uniquely identifies this application.
// Do not use the same AppId value in installers for other applications.
// (To generate a new GUID, click Tools | Generate GUID inside the IDE.)

AppId={{395C807B-D040-4B01-9AB5-2A9987174C22}
AppName={#MyAppName}
AppVersion={#MyAppVersion}
// AppVerName={#MyAppName} {#MyAppVersion}
AppPublisher={#MyAppPublisher}
AppPublisherURL={#MyAppURL}
AppSupportURL={#MyAppURL}
AppUpdatesURL={#MyAppURL}
DefaultDirName=C:\NelsonTest\OOP\{#MyAppName}
DefaultGroupName={#MyAppName}
AllowNoIcons=yes
OutputDir=D:\Developers Delphi\Delphi Test Inno Setup\Test-1 (Install)
OutputBaseFilename=setup
Password=12345
Compression=lzma
SolidCompression=yes

[Languages]
Name: "english"; MessagesFile: "compiler:Default.isl"

[Tasks]
Name: "desktopicon"; Description: "{cm:CreateDesktopIcon}"; GroupDescription: "{cm:AdditionalIcons}"; Flags: unchecked;

[Files]
Source: "D:\Developers Delphi\Delphi Test Inno Setup\Test-1  (Install)\OOP.exe"; DestDir: "{app}"; Flags: ignoreversion;  BeforeInstall:MsgInstall;
// NOTE: Don't use "Flags: ignoreversion" on any shared system files

[Icons]
Name: "{group}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"
Name: "{commondesktop}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"; Tasks: desktopicon

[Run]
Filename: "{app}\{#MyAppExeName}"; Description:  "{cm:LaunchProgram,{#StringChange(MyAppName, '&', '&&')}}";  Flags: nowait postinstall skipifsilent

[code]
// Mensaje previo a la instalación
procedure MsgInstall();
begin
  MsgBox('Se Instalara el Programa: ' + CurrentFileName, mbInformation, MB_OK);
end;

// Realiza el Setup en función de un archivo de control
function InitializeSetup(): Boolean;
begin
  if FileExists('C:\NelsonTest\FileControl.txt') then 
  begin 
    MsgBox('Setup Cancelado por Existencia de Archivo de Control', mbInformation, MB_OK);
    Result := False;
  end
  else
    Result := True;
end;
El código anterior en Inno Setup 5.5.5 bajo Windows 7 Professional x32, permite instalar una aplicación en función de la existencia de un archivo de control.

Revisa esta información:
Espero sea útil :)

Nelson.

diegoferxmr 16-12-2014 21:25:00

Hola a todos.
Tengo el código así, pero no me funciona: (Ver la parte de ifFileExist)

Código Delphi [-]
; Script generated by the Inno Setup Script Wizard.
; SEE THE DOCUMENTATION FOR DETAILS ON CREATING INNO SETUP SCRIPT FILES!

#define MyAppName "Biable"
#define MyAppVersion "6.1"
#define MyAppPublisher "Visión Tecnológica S.A.S."
#define MyAppURL "http:..."

[Setup]
; NOTE: The value of AppId uniquely identifies this application.
; Do not use the same AppId value in installers for other applications.
; (To generate a new GUID, click Tools | Generate GUID inside the IDE.)
AppId={{XXXXXXXX-XXXXX-XXXXX-XXXXXXXXXX}
AppName={#MyAppName}
AppVersion={#MyAppVersion}
;AppVerName={#MyAppName} {#MyAppVersion}
AppPublisher={#MyAppPublisher}
AppPublisherURL={#MyAppURL}
AppSupportURL={#MyAppURL}
AppUpdatesURL={#MyAppURL}
DefaultDirName={pf}\Vision Tecnologica
LicenseFile=\\URL
InfoBeforeFile=\\URL
OutputBaseFilename=biabledemo
Compression=lzma
SolidCompression=yes
ShowLanguageDialog=no
LanguageDetectionMethod=none
PrivilegesRequired=none
AllowRootDirectory=True
MinVersion=4.10,5.01
DisableProgramGroupPage=auto
SetupLogging=yes
AlwaysShowGroupOnReadyPage=True
AlwaysShowDirOnReadyPage=True
DisableDirPage=auto
DefaultGroupName=Biable 6.1

[Languages]
Name: "spanish"; MessagesFile: "compiler:Languages\Spanish.isl"

[Files]
Source: "\\URL*"; DestDir: "{app}"; Flags: ignoreversion createallsubdirs recursesubdirs
Source: "\\URL*"; DestDir: "{app}\Asistencia"; Flags: onlyifdoesntexist createallsubdirs recursesubdirs; MinVersion: 0,6.0
Source: "\\URL\*"; DestDir: "{commondocs}\Vision Tecnologica\Biable"; Flags: ignoreversion createallsubdirs recursesubdirs
; NOTE: Dont use "Flags: ignoreversion" on any shared system files
Source: "\\URL.dll"; DestDir: "{app}\Biable61"; Flags: regserver
Source: "\\URL*"; DestDir: "{userappdata}\Vision Tecnologica\Biable"; Flags: onlyifdoesntexist createallsubdirs recursesubdirs; MinVersion: 0,6.0
Source: "\\URL\*"; DestDir: "{userappdata}\Vision Tecnologica\Biable"; Flags: onlyifdoesntexist createallsubdirs recursesubdirs; OnlyBelowVersion: 0,6.0
Source: "c:\prj\Biable6\exe\insutils.dll"; Flags: dontcopy

[Icons]
Name: "{group}\Bienvenido a Biable"; Filename: "{commondocs}\Vision Tecnologica\Biable\Ejemplos\Bienvenido.xls"
Name: "{group}\Menú de Ejemplos"; Filename: "{commondocs}\Vision Tecnologica\Biable\Libros Ejemplo Biable.xls"
Name: "{group}\Asistencia Remota"; Filename: "{app}\Asistencia\vtsoporte.exe"
Name: "{group}\Asistencia Remota (Version 3)"; Filename: "{app}\Asistencia\vtsoporte3.exe"
Name: "{group}\Manual de Usuario"; Filename: "{app}\Biable\Ayuda\Manual de Usuario.pdf"
Name: "{group}\{cm:ProgramOnTheWeb,{#MyAppName}}"; Filename: "{#MyAppURL}"
Name: "{group}\{cm:UninstallProgram,{#MyAppName}}"; Filename: "{uninstallexe}"
Name: "{group}\Carpeta de Configuración"; Filename: "{commondocs}\Vision Tecnologica\Biable"; Languages: spanish
Name: "{group}\Ayuda Local"; Filename: "{app}\Biable\Ayuda\Biable.chm"

[Run]
Filename: "{commondocs}\Vision Tecnologica\Biable\Ejemplos\Bienvenido.xls"; Flags: nowait postinstall runasoriginaluser shellexec; Description: "Ejecutar Microsoft Excel"

[code]
#include "addins.iss"

 function  GenerateNewID(AppName: AnsiString): integer; 
 external 'GenerateNewID@files:insutils.dll stdcall setuponly delayload';

//*******************************************************************************
procedure MsgInstall();
begin
  MsgBox('Se Instalara el Programa: ' + CurrentFileName, mbInformation, MB_OK);
end;

// Realiza el Setup en función de un archivo de control
function InitializeSetup(): Boolean;
begin
  if FileExists('{app}\Biable\Biable.xla') then 
  begin 
    MsgBox('Setup Cancelado por Existencia de archivo de Biable', mbInformation, MB_OK);
    Result := False;
  end
  else
    Result := True;
end;
//*******************************************************************************
(*
  Called during Setup's initialization. Return False to abort Setup, True otherwise.
*)
begin
  Log( 'InitializeSetup' );
  // Default.
  //
  Result := true;
  // The Add-In does not (yet) work with 64-bit Excel. We warn and Exit immediately.
  //
  If IsExcel64Bit() then begin
    MsgBox('Este equipo tiene instalado Microsoft Excel a 64-bits y no está soportado.' + #13#10 + #13#10 +
      '{#MyAppName} está diseñando para trabajar con Microsoft Excel 32-bits solamente ' +
      'y no se instalará. Instale Microsoft Excel 32-bits y ejecute de nuevo la instalación de {#MyAppName}.' + #13#10 + #13#10 +
      'Contacte al personal de sistemas para recibir asistencia.', mbInformation, mb_Ok);
    Result := false;
    Exit;
  end;
  // Load previous choices
  //
//  InstallMode := StrToIntDef(GetPreviousData('InstallMode', '0'), 0);
//  SamplesPath := GetPreviousData('SamplesPath', GetExpandedConstant('{userdocs}', '{commondocs}', '') + '\My {#TheAppVeryShortName} Projects\Samples');
//  HTMLHelpPath := GetPreviousData('HTMLHelpPath', GetExpandedConstant('{sd}', '', '') + '\{#TheAppVeryShortName} HTML Help');
//  LexiconPath := GetPreviousData('LexiconPath', GetExpandedConstant('{userdocs}', '{commondocs}', '') + '\My {#TheAppVeryShortName} Lexicons');
end;



procedure DoPostInstall(  );
(*
  Post-Installation procedure. Runs after performing all installation actions.
*)
var
  ExcelAddInFullName: String;
begin
  Log( 'PostInstall' );
  GenerateNewID( '{#MyAppName}' );
  ExcelAddInFullName := ExpandConstant('{app}') + '\{#MyAppName}\{#MyAppName}.xla';
  Log( 'DoPostInstall ' + ExcelAddInFullName );   
  HookAddinToExcel( '{#MyAppName}.xla', ExcelAddInFullName );
end;


procedure DoSuccessInstall();
(*
  Successful Installation procedure. Runs after performing all actions.
*)
var
  TrustAddInsAndTemplates: Boolean;
  TrustVBProject: Boolean;
  MsgBoxResult: Integer;
begin
  Log( 'DoSuccessInstall' );
  // Check Trust to Add-Ins and Templates (for all versions)
  //
  TrustAddInsAndTemplates := IsTrustAddInsAndTemplatesChecked;

  // Check in Access To Visual Basic Project is enabled in Excel.
  // Note: Excel 2000 does not have this setting.
  //
  if (GetExcelVersionNumberAsNumber >= 10) then begin
    TrustVBProject := IsTrustVBProjectChecked;
  end else begin
    TrustVBProject := true;
  end;

  // If one of the 2 is not set, then issue a warning message.
  //
  if not TrustAddInsAndTemplates or not TrustVBProject then begin
    if IsRunningSilent then begin
      Log('Warning: Macro Security Trust settings not properly set. {#MyAppName} may not work properly.');
    end else begin
      // Just a message.
      // Comment this statement and uncomment next statement if you want to set.
      //
      MsgBoxResult := MsgBox('Information: Macro Security Trust settings not properly set.' + #13#10 + #13#10 +
        'To operate with {#MyAppName}, the Trust settings in the Macro Security must be set differently.' + #13#10 + #13#10 +
        'Contact a System Administrator for assistance.', mbInformation, mb_Ok);

//      // A question whether this shall be turned on right now?
//      // Uncomment this statement and comment previous statement if you want to set.
//      //
//      MsgBoxResult := MsgBox('Information: Macro Security Trust settings not properly set.' + #13#10 + #13#10 +
//        'To operate with {#MyAppName}, the Trust settings in the Macro Security must be set differently.' + #13#10 + #13#10 +
//        'Would you like to do this right now?', mbConfirmation, mb_YesNo);
//      //
//      if (MsgBoxResult = IDYES) then begin
//        if not SetTrustAddInsAndTemplates and not SetTrustVBProject then begin
//          MsgBox('Warning: could not set required Macro Security Trust settings.' + #13#10 + #13#10 +
//            'You may not have sufficient privileges to perform this action. Before you can operate with' + #13#10 +
//            '{#MyAppName}, remember to check and/or set these setting in Microsoft Excel.' + #13#10 + #13#10 +
//            'Contact a System Administrator for assistance.', mbInformation, mb_Ok);
//        end;
//      end;
    end;
  end;
end;


procedure CurStepChanged(CurStep: TSetupStep);
begin
  case CurStep of
//  ssInstall:
//    DoPreInstall();
  ssPostInstall:
    DoPostInstall();
  ssDone:
    DoSuccessInstall();
  end;
end;

Gracias por su ayuda.

nlsgarcia 17-12-2014 00:17:41

diegoferxmr,

Cita:

Empezado por diegoferxmr
...no me funciona...if FileExists('{app}\Biable\Biable.xla') then...

:rolleyes:

Te comento:

1- La constante (app) no puede ser usada directamente, debe ser expandida por medio de la función ExpandConstant.

2- La constante (app) no puede ser usada antes de ser inicializada, en el Event Functions InitializeSetup, esta no ha sido inicializada.

3- Te sugiero colocar el archivo de control en otro directorio, por ejemplo:
Código Delphi [-]
// Realiza el Setup en función de un archivo de control
function InitializeSetup(): Boolean;
begin  
  if FileExists(ExpandConstant('{sys}') + '\' + 'FileControl.txt') then   
  begin 
    MsgBox('Setup Cancelado por Existencia de Archivo de Control', mbInformation, MB_OK);
    Result := False;
  end
  else
    Result := True;
end;
Buscara el archivo de control en X:\Windows\System32, donde X será el drive donde este instalado Windows.

Espero sea útil :)

Nelson.


La franja horaria es GMT +2. Ahora son las 08:00:20.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
Traducción al castellano por el equipo de moderadores del Club Delphi