public void StartInstall()
        {
            MsiInstaller msiInterface = Globals.Instance.MsiInterface;

            msiInterface.InstallerMessageReceived += new EventHandler <InstallerMessageEventArgs>(msiInterface_InstallerMessageReceived);
            msiInterface.MessageLogged            += new EventHandler <LogMessage>(msiInterface_MessageLogged);

            switch (Globals.Instance.SelectedInstallType)
            {
            case InstallType.Install:
                msiInterface.Update(Globals.Instance.InstallFeatures, Globals.Instance.UninstallFeatures);
                break;

            case InstallType.InstallAll:
                msiInterface.Install(); break;

            case InstallType.Remove:
                msiInterface.Uninstall(Globals.Instance.UninstallFeatures); break;

            case InstallType.RemoveAll:
                msiInterface.Uninstall(); break;

            case InstallType.Repair: msiInterface.Repair(); break;

            case InstallType.Change:
                msiInterface.Update(Globals.Instance.InstallFeatures, Globals.Instance.UninstallFeatures);
                break;
            }
        }
        public virtual IInstaller get_installer_type(RegistryApplicationKey key, string uninstallExe, string uninstallArgs)
        {
            IInstaller installer = new CustomInstaller();

            switch (key.InstallerType)
            {
            case InstallerType.Msi:
                installer = new MsiInstaller();
                break;

            case InstallerType.InnoSetup:
                installer = new InnoSetupInstaller();
                break;

            case InstallerType.Nsis:
                installer = new NsisInstaller();
                break;

            case InstallerType.InstallShield:
                installer = new InstallShieldInstaller();
                break;
            }

            return(installer);
        }
Esempio n. 3
0
        private void btnCreateInstallerandDt_Click(object sender, EventArgs e)
        {
            ////Setup the installer and it's contents
            Content      content      = new Content();
            MsiInstaller msiInstaller = new MsiInstaller();

            FileInfo file = new FileInfo(txtMSILocation.Text);

            content.Location = file.Directory.FullName;
            ////use the msi folders location as the content source for the application package
            content = ContentImporter.CreateContentFromFolder(file.Directory.FullName);
            ////set the command that will run to install on a clients desktop
            msiInstaller.InstallCommandLine   = txtInstallCommandLine.Text;
            msiInstaller.UninstallCommandLine = txtUninstallCommandLine.Text;
            ContentRef contentReferenece = new ContentRef(content);

            content.OnFastNetwork           = ContentHandlingMode.Download;
            content.OnSlowNetwork           = ContentHandlingMode.DoNothing;
            content.FallbackToUnprotectedDP = false;
            ////configure other properties - for instance the produce code which by default is used to detect whether the application is already installed
            msiInstaller.Contents.Add(content);
            msiInstaller.InstallContent          = contentReferenece;
            msiInstaller.DetectionMethod         = DetectionMethod.ProductCode;
            msiInstaller.ProductCode             = txtProductCode.Text;
            msiInstaller.SourceUpdateProductCode = txtProductCode.Text;
            msiInstaller.ExecutionContext        = sccm.ExecutionContext.System;
            msiInstaller.Contents[0].PinOnClient = false;
            msiInstaller.Contents[0].PeerCache   = false;
            msiInstaller.UserInteractionMode     = UserInteractionMode.Normal;
            msiInstaller.MaxExecuteTime          = 120;
            msiInstaller.ExecuteTime             = 0;

            ////Add a deployment type to the application using the installer details created above

            sccm.DeploymentType dt = new sccm.DeploymentType(msiInstaller, "MSI", NativeHostingTechnology.TechnologyId);
            dt.Title   = txtSCCMApplicationName.Text;
            dt.Version = 1;
            ////retrieve tha application here to then add the deployment type to ot
            sccm.Application application = GetApplicationFromName(txtSCCMApplicationName.Text);
            application.DeploymentTypes.Add(dt);
            ////resave the application
            SaveApplication(application);
        }
        public virtual IInstaller get_installer_type(RegistryApplicationKey key, string uninstallExe, string uninstallArgs)
        {
            IInstaller installer = new CustomInstaller();

            switch (key.InstallerType)
            {
                case InstallerType.Msi:
                    installer = new MsiInstaller();
                    break;
                case InstallerType.InnoSetup:
                    installer = new InnoSetupInstaller();
                    break;
                case InstallerType.Nsis:
                    installer = new NsisInstaller();
                    break;
                case InstallerType.InstallShield:
                    installer = new InstallShieldInstaller();
                    break;
            }

            return installer;
        }
        public void run(PackageResult packageResult, ChocolateyConfiguration config)
        {
            if (!config.Features.AutoUninstaller)
            {
                this.Log().Info(" Skipping auto uninstaller - AutoUninstaller feature is not enabled.");
                return;
            }

            var pkgInfo = _packageInfoService.get_package_information(packageResult.Package);

            if (pkgInfo.RegistrySnapshot == null)
            {
                this.Log().Info(" Skipping auto uninstaller - No registry snapshot.");
                return;
            }

            var registryKeys = pkgInfo.RegistrySnapshot.RegistryKeys;

            if (registryKeys == null || registryKeys.Count == 0)
            {
                this.Log().Info(" Skipping auto uninstaller - No registry keys in snapshot.");
                return;
            }

            this.Log().Info(" Running auto uninstaller...");
            if (WaitForCleanup)
            {
                this.Log().Debug("Sleeping for {0} seconds to allow Windows to finish cleaning up.".format_with(SLEEP_TIME));
                Thread.Sleep((int)TimeSpan.FromSeconds(SLEEP_TIME).TotalMilliseconds);
            }

            foreach (var key in registryKeys.or_empty_list_if_null())
            {
                this.Log().Debug(() => " Preparing uninstall key '{0}'".format_with(key.UninstallString));

                if ((!string.IsNullOrWhiteSpace(key.InstallLocation) && !_fileSystem.directory_exists(key.InstallLocation)) || !_registryService.installer_value_exists(key.KeyPath, ApplicationParameters.RegistryValueInstallLocation))
                {
                    this.Log().Info(" Skipping auto uninstaller - The application appears to have been uninstalled already by other means.");
                    this.Log().Debug(() => " Searched for install path '{0}' - found? {1}".format_with(key.InstallLocation.escape_curly_braces(), _fileSystem.directory_exists(key.InstallLocation)));
                    this.Log().Debug(() => " Searched for registry key '{0}' value '{1}' - found? {2}".format_with(key.KeyPath.escape_curly_braces(), ApplicationParameters.RegistryValueInstallLocation, _registryService.installer_value_exists(key.KeyPath, ApplicationParameters.RegistryValueInstallLocation)));
                    continue;
                }

                // split on " /" and " -" for quite a bit more accuracy
                IList <string> uninstallArgsSplit = key.UninstallString.to_string().Split(new[] { " /", " -" }, StringSplitOptions.RemoveEmptyEntries).ToList();
                var            uninstallExe       = uninstallArgsSplit.DefaultIfEmpty(string.Empty).FirstOrDefault();
                var            uninstallArgs      = key.UninstallString.to_string().Replace(uninstallExe.to_string(), string.Empty);
                uninstallExe = uninstallExe.remove_surrounding_quotes();
                this.Log().Debug(() => " Uninstaller path is '{0}'".format_with(uninstallExe));


                IInstaller installer = new CustomInstaller();

                switch (key.InstallerType)
                {
                case InstallerType.Msi:
                    installer = new MsiInstaller();
                    break;

                case InstallerType.InnoSetup:
                    installer = new InnoSetupInstaller();
                    break;

                case InstallerType.Nsis:
                    installer = new NsisInstaller();
                    break;

                case InstallerType.InstallShield:
                    installer = new InstallShieldInstaller();
                    break;
                }

                this.Log().Debug(() => " Installer type is '{0}'".format_with(installer.GetType().Name));

                if (key.InstallerType == InstallerType.Msi)
                {
                    // because sometimes the key is set with /i to allow for modify :/
                    uninstallArgs = uninstallArgs.Replace("/I{", "/X{");
                    uninstallArgs = uninstallArgs.Replace("/i{", "/X{");
                    uninstallArgs = uninstallArgs.Replace("/I ", "/X ");
                    uninstallArgs = uninstallArgs.Replace("/i ", "/X ");
                }

                if (!key.HasQuietUninstall)
                {
                    //todo: ultimately we should merge keys
                    uninstallArgs += " " + installer.build_uninstall_command_arguments();
                }

                var logLocation = _fileSystem.combine_paths(_fileSystem.get_full_path(config.CacheLocation), "chocolatey", pkgInfo.Package.Id, pkgInfo.Package.Version.to_string());
                _fileSystem.create_directory_if_not_exists(_fileSystem.get_directory_name(logLocation));
                uninstallArgs = uninstallArgs.Replace(InstallTokens.PACKAGE_LOCATION, logLocation);

                this.Log().Debug(() => " Args are '{0}'".format_with(uninstallArgs));

                if (!key.HasQuietUninstall && installer.GetType() == typeof(CustomInstaller))
                {
                    var skipUninstaller = true;
                    if (config.PromptForConfirmation)
                    {
                        var selection = InteractivePrompt.prompt_for_confirmation("Uninstall may not be silent (could not detect). Proceed?", new[] { "yes", "no" }, defaultChoice: null, requireAnswer: true);
                        if (selection.is_equal_to("no"))
                        {
                            skipUninstaller = false;
                        }
                    }

                    if (skipUninstaller)
                    {
                        this.Log().Info(" Skipping auto uninstaller - Installer type was not detected and no silent uninstall key exists.");
                        return;
                    }
                }

                var exitCode = _commandExecutor.execute(
                    uninstallExe,
                    uninstallArgs.trim_safe(),
                    config.CommandExecutionTimeoutSeconds,
                    (s, e) =>
                {
                    if (e == null || string.IsNullOrWhiteSpace(e.Data))
                    {
                        return;
                    }
                    this.Log().Info(() => " [AutoUninstaller] {0}".format_with(e.Data));
                },
                    (s, e) =>
                {
                    if (e == null || string.IsNullOrWhiteSpace(e.Data))
                    {
                        return;
                    }
                    this.Log().Error(() => " [AutoUninstaller] {0}".format_with(e.Data));
                },
                    updateProcessPath: false);

                if (!installer.ValidUninstallExitCodes.Contains(exitCode))
                {
                    Environment.ExitCode = exitCode;
                    string logMessage = " Auto uninstaller failed. Please remove machine installation manually.{0} Exit code was {1}".format_with(Environment.NewLine, exitCode);
                    this.Log().Error(() => logMessage);
                    packageResult.Messages.Add(new ResultMessage(config.Features.FailOnAutoUninstaller ? ResultType.Error : ResultType.Warn, logMessage));
                }
                else
                {
                    this.Log().Info(() => " Auto uninstaller has successfully uninstalled {0} or detected previous uninstall.".format_with(packageResult.Package.Id));
                }
            }
        }
Esempio n. 6
0
        public void run(PackageResult packageResult, ChocolateyConfiguration config)
        {
            if (!config.Features.AutoUninstaller)
            {
                this.Log().Info(" Skipping auto uninstaller - AutoUninstaller feature is not enabled.");
                return;
            }

            var pkgInfo = _packageInfoService.get_package_information(packageResult.Package);

            if (pkgInfo.RegistrySnapshot == null)
            {
                this.Log().Info(" Skipping auto uninstaller - No registry snapshot.");
                return;
            }

            var registryKeys = pkgInfo.RegistrySnapshot.RegistryKeys;

            if (registryKeys == null || registryKeys.Count == 0)
            {
                this.Log().Info(" Skipping auto uninstaller - No registry keys in snapshot.");
                return;
            }

            this.Log().Info(" Running auto uninstaller...");

            foreach (var key in registryKeys.or_empty_list_if_null())
            {
                this.Log().Debug(() => " Preparing uninstall key '{0}'".format_with(key.UninstallString));

                if ((!string.IsNullOrWhiteSpace(key.InstallLocation) && !_fileSystem.directory_exists(key.InstallLocation)) || !_registryService.value_exists(key.KeyPath, ApplicationParameters.RegistryValueInstallLocation))
                {
                    this.Log().Info(" Skipping auto uninstaller - The application appears to have been uninstalled already by other means.");
                    this.Log().Debug(() => " Searched for install path '{0}' - found? {1}".format_with(key.InstallLocation.escape_curly_braces(), _fileSystem.directory_exists(key.InstallLocation)));
                    this.Log().Debug(() => " Searched for registry key '{0}' value '{1}' - found? {2}".format_with(key.KeyPath.escape_curly_braces(), ApplicationParameters.RegistryValueInstallLocation, _registryService.value_exists(key.KeyPath, ApplicationParameters.RegistryValueInstallLocation)));
                    continue;
                }

                // split on " /" and " -" for quite a bit more accuracy
                IList <string> uninstallArgsSplit = key.UninstallString.to_string().Split(new[] { " /", " -" }, StringSplitOptions.RemoveEmptyEntries).ToList();
                var            uninstallExe       = uninstallArgsSplit.DefaultIfEmpty(string.Empty).FirstOrDefault();
                var            uninstallArgs      = key.UninstallString.to_string().Replace(uninstallExe.to_string(), string.Empty);
                uninstallExe = uninstallExe.remove_surrounding_quotes();
                this.Log().Debug(() => " Uninstaller path is '{0}'".format_with(uninstallExe));

                if (!key.HasQuietUninstall)
                {
                    IInstaller installer = new CustomInstaller();

                    switch (key.InstallerType)
                    {
                    case InstallerType.Msi:
                        installer = new MsiInstaller();
                        break;

                    case InstallerType.InnoSetup:
                        installer = new InnoSetupInstaller();
                        break;

                    case InstallerType.Nsis:
                        installer = new NsisInstaller();
                        break;

                    case InstallerType.InstallShield:
                        installer = new InstallShieldInstaller();
                        break;

                    default:
                        // skip
                        break;
                    }

                    this.Log().Debug(() => " Installer type is '{0}'".format_with(installer.GetType().Name));


                    //todo: ultimately we should merge keys with logging
                    uninstallArgs += " " + installer.build_uninstall_command_arguments();
                }

                if (key.InstallerType == InstallerType.Msi)
                {
                    //because sometimes the key is set with /i to allow for modify :/
                    uninstallArgs = uninstallArgs.Replace("/I{", "/X{");
                    uninstallArgs = uninstallArgs.Replace("/i{", "/X{");
                    uninstallArgs = uninstallArgs.Replace("/I ", "/X ");
                    uninstallArgs = uninstallArgs.Replace("/i ", "/X ");
                }

                this.Log().Debug(() => " Args are '{0}'".format_with(uninstallArgs));

                var exitCode = _commandExecutor.execute(
                    uninstallExe,
                    uninstallArgs.trim_safe(),
                    config.CommandExecutionTimeoutSeconds,
                    (s, e) =>
                {
                    if (e == null || string.IsNullOrWhiteSpace(e.Data))
                    {
                        return;
                    }
                    this.Log().Debug(() => " [AutoUninstaller] {0}".format_with(e.Data));
                },
                    (s, e) =>
                {
                    if (e == null || string.IsNullOrWhiteSpace(e.Data))
                    {
                        return;
                    }
                    this.Log().Error(() => " [AutoUninstaller] {0}".format_with(e.Data));
                },
                    updateProcessPath: false);

                if (exitCode != 0)
                {
                    Environment.ExitCode = exitCode;
                    string logMessage = " Auto uninstaller failed. Please remove machine installation manually.";
                    this.Log().Error(() => logMessage);
                    packageResult.Messages.Add(new ResultMessage(ResultType.Error, logMessage));
                }
                else
                {
                    this.Log().Info(() => " Auto uninstaller has successfully uninstalled {0} from your machine.".format_with(packageResult.Package.Id));
                }
            }
        }
Esempio n. 7
0
        void InstallThreadHandler()
        {
            try
            {
                Trace.WriteLine("Thread");
                Assembly curAssm;
                curAssm = Assembly.GetAssembly(this.GetType());
                int  registertimeout = 0;
                bool wmiregistered   = false;
                while (registertimeout < 30 * 1000)
                {
                    Trace.WriteLine("Try to register WMI");
                    try
                    {
                        if (System.Management.Instrumentation.Instrumentation.IsAssemblyRegistered(curAssm))
                        {
                            //Cool; it's already registered in WMI
                            Trace.WriteLine("Already registered");
                            wmiregistered = true;
                            break;
                        }
                        else //Well then, register it
                        {
                            Trace.WriteLine("Ensure we are registered with WMI");

                            System.Management.Instrumentation.Instrumentation.RegisterAssembly(curAssm);
                            wmiregistered = true;
                            break;
                        }
                    }
                    catch (ManagementException)
                    {
                        Trace.WriteLine("Waiting for WMI to initialise");
                        Thread.Sleep(500);
                        registertimeout += 500;
                    }
                    catch (Exception e)
                    {
                        Trace.WriteLine("WMI initialisation not finished (" + e.ToString() + ")");
                        Thread.Sleep(500);
                        registertimeout += 500;
                    }
                }
                if (!wmiregistered)
                {
                    Trace.WriteLine("Unable to contact WMI");
                    InstallState.Fail("Unable to contact WMI");
                }
                Trace.WriteLine("Got WMI connection");
                CitrixXenServerInstallStatus installstatusclass = new CitrixXenServerInstallStatus(InstallState);
                Trace.WriteLine("got status");
                try
                {
                    Instrumentation.Publish(installstatusclass);
                }
                catch (Exception e)
                {
                    Trace.WriteLine(e.ToString());
                    throw;
                }
                Trace.WriteLine("Begin");
                while (InstallState.PauseOnStart)
                {
                    Trace.WriteLine("Paused");
                    Thread.Sleep(1000);
                    try
                    {
                        int pausestate = (int)Application.CommonAppDataRegistry.GetValue("Continue", 0);
                        if (pausestate != 0)
                        {
                            break;
                        }
                    }
                    catch { };
                }
                ;
                InstallState.MaxProgress = 100;
                InstallState.Progress    = 1;
                Trace.WriteLine("Initializing Install =======================================");

                InstallerState.ExistingDriverInstalling = false;
                uint res = setupapi.CMP_WaitNoPendingInstallEvents(0);
                if (res == setupapi.WAIT_TIMEOUT || res == setupapi.WAIT_FAILED)
                {
                    InstallerState.ExistingDriverInstalling = true;
                    Registry.SetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Citrix\\XenToolsInstaller", "existingDriverInstalling", 1, RegistryValueKind.DWord);
                }
                Trace.WriteLine("check reg");
                Object regval = Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Citrix\\XenToolsInstaller", "existingDriverInstalling", 0);

                if (regval != null && ((int)regval) == 1)
                {
                    Trace.WriteLine("set from reg");
                    InstallerState.ExistingDriverInstalling = true;
                }
                Trace.WriteLine("reg done");

                DriverPackage DriversMsi;
                MsiInstaller  VssProvMsi;
                MsiInstaller  AgentMsi;
                string        installdir;
                NSISItem      InstallerNSIS;
                if (is64BitOS())
                {
                    Trace.WriteLine("64 Bit Install");
                    installdir = (string)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Citrix\\XenToolsInstaller", "Install_Dir", Application.StartupPath);
                    DriversMsi = new DriverPackage((string)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Citrix\\XenToolsInstaller", "MSISourceDir", Application.StartupPath), Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Citrix\\XenToolsInstaller", "MSISourceDir", Application.StartupPath) + "citrixxendriversx64.msi");
                    VssProvMsi = new MsiInstaller(Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Citrix\\XenToolsInstaller", "MSISourceDir", Application.StartupPath) + "citrixvssx64.msi");
                    AgentMsi   = new MsiInstaller(Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Citrix\\XenToolsInstaller", "MSISourceDir", Application.StartupPath) + "citrixguestagentx64.msi");

                    InstallerNSIS = new NSISItem("Citrix XenTools", (string)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Citrix\\XenToolsInstaller", "MSISourceDir", Application.StartupPath));
                }
                else
                {
                    Trace.WriteLine("32 Bit Install");
                    installdir = (string)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Citrix\\XenToolsInstaller", "Install_Dir", Application.StartupPath);
                    DriversMsi = new DriverPackage((string)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Citrix\\XenToolsInstaller", "MSISourceDir", Application.StartupPath), Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Citrix\\XenToolsInstaller", "MSISourceDir", Application.StartupPath) + "citrixxendriversx86.msi");
                    VssProvMsi = new MsiInstaller(Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Citrix\\XenToolsInstaller", "MSISourceDir", Application.StartupPath) + "citrixvssx86.msi");
                    AgentMsi   = new MsiInstaller(Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Citrix\\XenToolsInstaller", "MSISourceDir", Application.StartupPath) + "citrixguestagentx86.msi");

                    InstallerNSIS = new NSISItem("Citrix XenTools", (string)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Citrix\\XenToolsInstaller", "MSISourceDir", Application.StartupPath));
                }
                installdir = "\"" + installdir + "\"";

                VifConfig Vif = new VifConfig();
                Trace.WriteLine("Entering state loop");
                Dictionary <string, int[]> prog = new Dictionary <string, int[]>();

                prog["installscore"]     = new int[] { 300, 0 };
                prog["tempscore"]        = new int[] { 0, 0 };
                InstallState.MaxProgress = prog["installscore"][0];

                if (InstallService.isWOW64())
                {
                    Trace.WriteLine("Install failed");
                    InstallState.Fail("PV Tools cannot be installed on systems where .Net applications are forced to run under WoW64\n\nSet HKEY_LOCAL_MACHINE\\Software\\Microsoft\\.NetFramework\\Enable64Bit to 1 and attempt the install again.");
                }

                while ((!InstallState.Failed) && (InstallState.RebootCount > 0) && (!InstallState.Done))
                {
                    InstallState.Unchanged  = true;
                    prog["installscore"][1] = 0;
                    if (InstallState.GotAgent)
                    {
                        prog["installscore"][1] += 100;
                    }
                    if (InstallState.NsisFree)
                    {
                        prog["installscore"][1] += 100;
                    }
                    if (InstallState.GotDrivers)
                    {
                        prog["installscore"][1] += 100;
                    }
                    InstallState.MaxProgress = prog["installscore"][0] + prog["tempscore"][0];
                    InstallState.Progress    = prog["installscore"][1] + prog["tempscore"][1];

                    if (InstallState.GotAgent &&
                        ((InstallWizard.InstallerState.WinVersion.isServerSKU() && InstallState.GotVssProvider) || !InstallWizard.InstallerState.WinVersion.isServerSKU()) &&
                        InstallState.GotDrivers &&
                        !InstallState.RebootNow &&
                        InstallState.NsisFree &&
                        !InstallState.NeedsReboot)
                    {
                        Trace.WriteLine("Everything is installed");
                        InstallState.Installed = true;
                        InstallState.Done      = true;
                        continue;
                    }

                    if ((!InstallState.GotDrivers) && (InstallState.NsisFree))
                    {
                        Trace.WriteLine("Check if drivers are functioning");

                        string oldtext = InstallState.DriverText;

                        if ((DriversMsi.installed() && (!DriversMsi.olderinstalled())) && DriversMsi.functioning(ref InstallState.DriverText))
                        {
                            Trace.WriteLine("Drivers functioning");
                            InstallState.GotDrivers = true;
                        }
                        else
                        {
                            if (InstallState.DriverText != oldtext)
                            {
                                InstallState.PollingReset();
                            }
                            if ((!InstallState.DriversPlaced) && ((!DriversMsi.installed()) || DriversMsi.olderinstalled()))
                            {
                                Trace.WriteLine("Driver install package not found");
                                Trace.WriteLine("Attempt driver install");
                                Trace.WriteLine(DriversMsi.ToString());

                                if (DriversMsi.olderinstalled())
                                {
                                }

                                try
                                {
                                    DriversMsi.install("INSTALLDIR=" + installdir, "driversmsi", InstallState);
                                    InstallState.DriversPlaced = true;
                                    InstallState.NeedsReboot   = true;
                                    InstallState.Polling       = true;
                                    Trace.WriteLine("Install success");
                                    continue;
                                }
                                catch (InstallerException e)
                                {
                                    Trace.WriteLine("Install failed");
                                    InstallState.Fail("Failed to install drivers: " + e.ErrorMessage);
                                    continue;
                                }
                            }
                            else
                            {
                                if ((!InstallState.DriversPlaced) && InstallState.NotRebooted)
                                {
                                    DriversMsi.repair();
                                    Trace.WriteLine("Repair done");
                                    InstallState.DriversPlaced = true;
                                    InstallState.NeedsReboot   = true;
                                    InstallState.Polling       = true;
                                    continue;
                                }
                                else
                                {
                                    Trace.WriteLine("Repair not needed");
                                }
                            }
                            if (!InstallState.RebootNow)
                            {
                                Trace.WriteLine("Wait to see if drivers initialize");
                                int noneedtoreboot = (int)Application.CommonAppDataRegistry.GetValue("DriverFinalReboot", 0);
                                if (noneedtoreboot == 0)
                                {
                                    Trace.WriteLine("Pool - I don't know if I have to reboot");
                                    InstallState.Polling = true;
                                }
                                else
                                {
                                    Trace.WriteLine("Don't poll, I have to reboot");
                                    InstallState.RebootNow = true;
                                }
                            }
                        }
                    }
                    else
                    {
                        Trace.WriteLine("No DriverMSI work");
                    }


                    if ((!InstallState.NsisFree) && (!InstallState.NsisHandlingRequired))
                    {
                        Trace.WriteLine("Checking NSIS");
                        if (InstallerNSIS.installed() || InstallerNSIS.nsisPartiallyInstalled())
                        {
                            Trace.WriteLine("NSIS is installed, and needs to be removed");
                            if (InstallState.RebootReady)
                            {
                                Trace.WriteLine("Removing NSIS");
                                Vif.CopyPV();
                                Trace.WriteLine("Attempting NSIS Uninstall");
                                InstallState.NsisHandlingRequired = true;
                                InstallState.RebootNow            = true;
                            }
                            else
                            {
                                Trace.WriteLine("We'll remove NSIS next reboot");
                                InstallState.RebootNow = true;
                            }
                        }
                        else
                        {
                            Trace.WriteLine("No NSIS based installer found");
                            InstallState.NsisFree = true;
                        }
                    }
                    else
                    {
                        Trace.WriteLine("No NSIS work");
                    }

                    if (DriverPackage.unknownDeviceInstalled())
                    {
                        InstallState.Fail("Unknown PV drivers installed on system.  Uninstall PV drivers and retry");
                        continue;
                    }


                    if (InstallWizard.InstallerState.WinVersion.isServerSKU())
                    {
                        if ((!InstallState.GotVssProvider) && (InstallState.NsisFree) && (!InstallState.NsisHandlingRequired))
                        {
                            Trace.WriteLine("Checking Vss Provider");
                            if (!VssProvMsi.installed())
                            {
                                Trace.WriteLine("Vss Provider not found, installing");
                                Trace.WriteLine(VssProvMsi.ToString());
                                try
                                {
                                    VssProvMsi.install("INSTALLDIR=" + installdir, "vssprov1msi", InstallState);
                                }
                                catch (InstallerException e)
                                {
                                    InstallState.Fail("Failed to install Vss  Provider : " + e.ErrorMessage);
                                    continue;
                                }
                            }
                            else if (VssProvMsi.olderinstalled())
                            {
                                Trace.WriteLine("Old Vss Provider found, updating");
                                try
                                {
                                    VssProvMsi.install("INSTALLDIR=" + installdir, "vssprov2msi", InstallState);
                                }
                                catch (InstallerException e)
                                {
                                    InstallState.Fail("Failed to install Vss Provider : " + e.ErrorMessage);
                                    continue;
                                }
                            }
                            else
                            {
                                Trace.WriteLine("Correct Vss Provider found");
                                InstallState.GotVssProvider = true;
                            }
                        }
                        else
                        {
                            Trace.WriteLine("No VSS Work");
                        }
                    }
                    else
                    {
                        Trace.WriteLine("No ServerSKU Work");
                    }

                    if ((!InstallState.GotAgent) && (InstallState.NsisFree) && (!InstallState.NsisHandlingRequired))
                    {
                        Trace.WriteLine("Checking Agent");
                        if (!AgentMsi.installed())
                        {
                            Trace.WriteLine("Agent not found, installing");
                            Trace.WriteLine(AgentMsi.ToString());
                            try
                            {
                                AgentMsi.install("INSTALLDIR=" + installdir, "agent1msi", InstallState);
                            }
                            catch (InstallerException e)
                            {
                                InstallState.Fail("Failed to install Guest Agent : " + e.ErrorMessage);
                                continue;
                            }
                        }
                        else if (AgentMsi.olderinstalled())
                        {
                            Trace.WriteLine("Old Agent found, updating");
                            try
                            {
                                AgentMsi.install("INSTALLDIR=" + installdir, "agent2msi", InstallState);
                            }
                            catch (InstallerException e)
                            {
                                InstallState.Fail("Failed to install Guest Agent : " + e.ErrorMessage);
                                continue;
                            }
                        }
                        else
                        {
                            Trace.WriteLine("Correct Agent found");
                            InstallState.GotAgent = true;
                        }
                    }
                    else
                    {
                        Trace.WriteLine("No Agent Work");
                    }

                    if (InstallState.Polling)
                    {
                        if (InstallState.PollTimedOut)
                        {
                            Trace.WriteLine("Polling timed out");
                            InstallState.RebootNow   = true;
                            InstallState.NeedsReboot = false;
                            InstallState.Polling     = false;
                        }
                        else
                        {
                            prog["tempscore"][1] += 1;
                            prog["tempscore"][0] += 1;
                            InstallState.Sleep(5000);
                        }
                    }
                    else
                    {
                        Trace.WriteLine("No Polling Work");
                    }

                    if ((!InstallState.RebootReady) && InstallState.RebootNow && InstallState.Unchanged)
                    {
                        // We are ready to reboot
                        Trace.WriteLine("Is anything preventing us from shutting down?");
                        if (InstallerState.ExistingDriverInstalling)
                        {
                            setupapi.CMP_WaitNoPendingInstallEvents(1000 * 20 * 60);
                        }
                        else
                        {
                            setupapi.CMP_WaitNoPendingInstallEvents(setupapi.INFINITE);
                        }

                        Trace.WriteLine("Ready to reboot");
                        InstallState.Polling       = false;
                        InstallState.RebootDesired = true;
                        if (InstallState.WaitForShutdown())
                        {
                            Trace.WriteLine("Shutdown occuring");
                        }
                        continue;
                    }
                    else
                    {
                        Trace.WriteLine("No rebootready work");
                    }

                    if (InstallState.RebootReady && InstallState.RebootNow && InstallState.Unchanged)
                    {
                        Trace.WriteLine("Expecting Reboot /  Shutdown");
                        InstallState.Rebooting = true;
                        if (InstallState.NsisHandlingRequired)
                        {
                            // Irritatingly, the NSIS installer continues running for longer than the
                            // lifetime of the uninstall.exe process.  Since we don't want to reboot
                            // while it (or its unattached children) are still running, we rely on
                            // the NSIS uninstaller to perform its own reboot, when it is done.
                            //
                            // We want to update George or earlier installers, as they don't
                            // uninstall silently
                            if (InstallerNSIS.installed() &&
                                ((InstallerNSIS.majorVersion() > 5) ||
                                 ((InstallerNSIS.majorVersion() == 5) && (InstallerNSIS.minorVersion() > 5))))
                            {
                                InstallerNSIS.uninstall();
                            }
                            else
                            {
                                // NSIS is installed, but the install is corrupt and the uninstaller can't be located
                                InstallerNSIS.update();

                                //NSIS returns the same errorlevel for 'failure to install' and for
                                // 'needs a reboot to install'.  So we have to presume the install
                                // was a success.
                            }
                            InstallState.RebootNow = false;
                            InstallState.Done      = true;
                        }
                        else
                        {
                            InstallState.Done      = true;
                            InstallState.RebootNow = false;
                            InstallState.DoShutdown();
                        }
                    }
                    else
                    {
                        Trace.WriteLine("No Shutdown work");
                    }
                }

                Trace.WriteLine("Exited install cycle " + InstallState.Failed + " " + InstallState.RebootCount + " " + InstallState.Done);

                if (!InstallState.Passive)
                {
                    // We want to wait until the user terminates the GUI installer before shutting down the service
                    InstallState.WaitForDone();
                }

                if (InstallState.Installed || InstallState.Cancelled || InstallState.Failed)
                {
                    Trace.WriteLine("Installed " + InstallState.Installed + " Cancelled " + InstallState.Cancelled + " Failed " + InstallState.Failed);

                    try
                    {
                        Registry.LocalMachine.OpenSubKey(@"Software").OpenSubKey("Microsoft").OpenSubKey("Windows").OpenSubKey("CurrentVersion").OpenSubKey("Run", true).DeleteValue("CitrixXenAgentInstaller");
                    }
                    catch (Exception e)
                    {
                        if (!InstallState.Passive)
                        {
                            Trace.WriteLine("Failed to remove install agent run subkey: " + e.ToString());
                            InstallState.Fail("Failed to remove install agent subkey");
                        }
                    }
                    Trace.WriteLine("Turn off DriverFinalReboot");
                    Application.CommonAppDataRegistry.SetValue("DriverFinalReboot", 0);

                    try
                    {
                        Registry.LocalMachine.OpenSubKey(@"HKEY_LOCAL_MACHINE\\SOFTWARE\\Citrix\\XenToolsInstaller", true).DeleteValue("existingDriverInstalling");
                    }
                    catch
                    {
                    }

                    Registry.SetValue(@"HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\XenPVInstall", "Start", 3);
                    (new Thread(delegate()
                    {
                        this.Stop();
                    })).Start();
                }
            }
            catch (Exception e)
            {
                Trace.WriteLine("Install exception :" + e.ToString());
                InstallState.Fail("Failed to install due to exception" + e.ToString());
                if (!InstallState.Passive)
                {
                    // We want to wait until the user terminates the GUI installer before shutting down the service

                    InstallState.WaitForDone();
                }
                try
                {
                    Registry.LocalMachine.OpenSubKey(@"Software").OpenSubKey("Microsoft").OpenSubKey("Windows").OpenSubKey("CurrentVersion").OpenSubKey("Run", true).DeleteValue("CitrixXenAgentInstaller");
                }
                catch {
                    Trace.WriteLine("Failed to remove install agent run subkey (error state)");
                    InstallState.Fail("Failed to remove install agent subkey");
                }
            }
        }
        public void run(PackageResult packageResult, ChocolateyConfiguration config)
        {
            if (!config.Features.AutoUninstaller)
            {
                this.Log().Info(" Skipping auto uninstaller - AutoUninstaller feature is not enabled.");
                return;
            }

            var pkgInfo = _packageInfoService.get_package_information(packageResult.Package);

            if (pkgInfo.RegistrySnapshot == null)
            {
                this.Log().Info(" Skipping auto uninstaller - No registry snapshot.");
                return;
            }

            var registryKeys = pkgInfo.RegistrySnapshot.RegistryKeys;
            if (registryKeys == null || registryKeys.Count == 0)
            {
                this.Log().Info(" Skipping auto uninstaller - No registry keys in snapshot.");
                return;
            }

            this.Log().Info(" Running auto uninstaller...");
            if (WaitForCleanup)
            {
                this.Log().Debug("Sleeping for {0} seconds to allow Windows to finish cleaning up.".format_with(SLEEP_TIME));
                Thread.Sleep((int)TimeSpan.FromSeconds(SLEEP_TIME).TotalMilliseconds);
            }
            
            foreach (var key in registryKeys.or_empty_list_if_null())
            {
                this.Log().Debug(() => " Preparing uninstall key '{0}'".format_with(key.UninstallString.escape_curly_braces()));

                if ((!string.IsNullOrWhiteSpace(key.InstallLocation) && !_fileSystem.directory_exists(key.InstallLocation)) || !_registryService.installer_value_exists(key.KeyPath, ApplicationParameters.RegistryValueInstallLocation))
                {
                    this.Log().Info(" Skipping auto uninstaller - The application appears to have been uninstalled already by other means.");
                    this.Log().Debug(() => " Searched for install path '{0}' - found? {1}".format_with(key.InstallLocation.escape_curly_braces(), _fileSystem.directory_exists(key.InstallLocation)));
                    this.Log().Debug(() => " Searched for registry key '{0}' value '{1}' - found? {2}".format_with(key.KeyPath.escape_curly_braces(), ApplicationParameters.RegistryValueInstallLocation, _registryService.installer_value_exists(key.KeyPath, ApplicationParameters.RegistryValueInstallLocation)));
                    continue;
                }

                // split on " /" and " -" for quite a bit more accuracy
                IList<string> uninstallArgsSplit = key.UninstallString.to_string().Split(new[] {" /", " -"}, StringSplitOptions.RemoveEmptyEntries).ToList();
                var uninstallExe = uninstallArgsSplit.DefaultIfEmpty(string.Empty).FirstOrDefault();
                var uninstallArgs = key.UninstallString.to_string().Replace(uninstallExe.to_string(), string.Empty);
                uninstallExe = uninstallExe.remove_surrounding_quotes();
                this.Log().Debug(() => " Uninstaller path is '{0}'".format_with(uninstallExe));


                IInstaller installer = new CustomInstaller();

                switch (key.InstallerType)
                {
                    case InstallerType.Msi:
                        installer = new MsiInstaller();
                        break;
                    case InstallerType.InnoSetup:
                        installer = new InnoSetupInstaller();
                        break;
                    case InstallerType.Nsis:
                        installer = new NsisInstaller();
                        break;
                    case InstallerType.InstallShield:
                        installer = new InstallShieldInstaller();
                        break;
                }

                this.Log().Debug(() => " Installer type is '{0}'".format_with(installer.GetType().Name));

                if (key.InstallerType == InstallerType.Msi)
                {
                    // because sometimes the key is set with /i to allow for modify :/
                    uninstallArgs = uninstallArgs.Replace("/I{", "/X{");
                    uninstallArgs = uninstallArgs.Replace("/i{", "/X{");
                    uninstallArgs = uninstallArgs.Replace("/I ", "/X ");
                    uninstallArgs = uninstallArgs.Replace("/i ", "/X ");
                }

                if (!key.HasQuietUninstall)
                {
                    //todo: ultimately we should merge keys
                    uninstallArgs += " " + installer.build_uninstall_command_arguments();
                }

                var logLocation = _fileSystem.combine_paths(_fileSystem.get_full_path(config.CacheLocation), "chocolatey", pkgInfo.Package.Id, pkgInfo.Package.Version.to_string());
                this.Log().Debug(() => " Setting up uninstall logging directory at {0}".format_with(logLocation.escape_curly_braces()));
                _fileSystem.create_directory_if_not_exists(_fileSystem.get_directory_name(logLocation));
                uninstallArgs = uninstallArgs.Replace(InstallTokens.PACKAGE_LOCATION, logLocation);

                this.Log().Debug(() => " Args are '{0}'".format_with(uninstallArgs.escape_curly_braces()));

                if (!key.HasQuietUninstall &&  installer.GetType() == typeof(CustomInstaller))
                {
                    var skipUninstaller = true;
                    if (config.PromptForConfirmation)
                    {
                        var selection = InteractivePrompt.prompt_for_confirmation(
                            "Uninstall may not be silent (could not detect). Proceed?",
                            new[] { "yes", "no" },
                            defaultChoice: null,
                            requireAnswer: true,
                            allowShortAnswer: true,
                            shortPrompt: true
                            );
                        if (selection.is_equal_to("yes")) skipUninstaller = false;
                    }

                    if (skipUninstaller)
                    {
                        this.Log().Info(" Skipping auto uninstaller - Installer type was not detected and no silent uninstall key exists.");
                        this.Log().Warn("If the application was not removed with a chocolateyUninstall.ps1,{0} please remove it from Programs and Features manually.".format_with(Environment.NewLine));
                        return;
                    }
                }

                var exitCode = _commandExecutor.execute(
                    uninstallExe,
                    uninstallArgs.trim_safe(),
                    config.CommandExecutionTimeoutSeconds,
                    (s, e) =>
                        {
                            if (e == null || string.IsNullOrWhiteSpace(e.Data)) return;
                            this.Log().Info(() => " [AutoUninstaller] {0}".format_with(e.Data.escape_curly_braces()));
                        },
                    (s, e) =>
                        {
                            if (e == null || string.IsNullOrWhiteSpace(e.Data)) return;
                            this.Log().Error(() => " [AutoUninstaller] {0}".format_with(e.Data.escape_curly_braces()));
                        },
                    updateProcessPath: false);

                if (!installer.ValidUninstallExitCodes.Contains(exitCode))
                {
                    Environment.ExitCode = exitCode;
                    string logMessage = " Auto uninstaller failed. Please remove machine installation manually.{0} Exit code was {1}".format_with(Environment.NewLine, exitCode);
                    this.Log().Error(() => logMessage.escape_curly_braces());
                    packageResult.Messages.Add(new ResultMessage(config.Features.FailOnAutoUninstaller ? ResultType.Error : ResultType.Warn, logMessage));
                }
                else
                {
                    this.Log().Info(() => " Auto uninstaller has successfully uninstalled {0} or detected previous uninstall.".format_with(packageResult.Package.Id));
                }
            }
        }
Esempio n. 9
0
        void InstallThreadHandler()
        {
            try
            {
                Trace.WriteLine("Thread");
                Assembly curAssm;
                curAssm = Assembly.GetAssembly(this.GetType());
                int  registertimeout = 0;
                bool wmiregistered   = false;
                while (registertimeout < 30 * 1000)
                {
                    Trace.WriteLine("Try to register WMI");
                    try
                    {
                        if (System.Management.Instrumentation.Instrumentation.IsAssemblyRegistered(curAssm))
                        {
                            //Cool; it's already registered in WMI
                            Trace.WriteLine("Already registered");
                            wmiregistered = true;
                            break;
                        }
                        else //Well then, register it
                        {
                            Trace.WriteLine("Ensure we are registered with WMI");

                            System.Management.Instrumentation.Instrumentation.RegisterAssembly(curAssm);
                            wmiregistered = true;
                            break;
                        }
                    }
                    catch (ManagementException)
                    {
                        Trace.WriteLine("Waiting for WMI to initialise");
                        Thread.Sleep(500);
                        registertimeout += 500;
                    }
                    catch (Exception e)
                    {
                        Trace.WriteLine("WMI initialisation not finished (" + e.ToString() + ")");
                        Thread.Sleep(500);
                        registertimeout += 500;
                    }
                }
                if (!wmiregistered)
                {
                    Trace.WriteLine("Unable to contact WMI");
                    InstallState.Fail("Unable to contact WMI");
                }
                Trace.WriteLine("Got WMI connection");
                CitrixXenServerInstallStatus installstatusclass = new CitrixXenServerInstallStatus(InstallState);
                Trace.WriteLine("got status");
                try
                {
                    Instrumentation.Publish(installstatusclass);
                }
                catch (Exception e)
                {
                    Trace.WriteLine(e.ToString());
                    throw;
                }
                Trace.WriteLine("Begin");
                while (InstallState.PauseOnStart)
                {
                    Trace.WriteLine("Paused");
                    Thread.Sleep(1000);
                    try
                    {
                        int pausestate = (int)Application.CommonAppDataRegistry.GetValue("Continue", 0);
                        if (pausestate != 0)
                        {
                            break;
                        }
                    }
                    catch { };
                }
                ;
                InstallState.MaxProgress = 100;
                InstallState.Progress    = 1;
                Trace.WriteLine("Initializing Install =======================================");


                HwidState     HWID = new HwidState(@"PCI\VEN_5853&DEV_0002&REV_02");
                DriverPackage DriversMsi;
                MsiInstaller  VssProvMsi;
                MsiInstaller  AgentMsi;
                string        installdir;
                NSISItem      InstallerNSIS;
                if (is64BitOS())
                {
                    Trace.WriteLine("64 Bit Install");
                    installdir = (string)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Citrix\\XenToolsInstaller", "Install_Dir", Application.StartupPath);
                    DriversMsi = new DriverPackage((string)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Citrix\\XenToolsInstaller", "MSISourceDir", Application.StartupPath), Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Citrix\\XenToolsInstaller", "MSISourceDir", Application.StartupPath) + "citrixxendriversx64.msi");
                    VssProvMsi = new MsiInstaller(Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Citrix\\XenToolsInstaller", "MSISourceDir", Application.StartupPath) + "citrixvssx64.msi");
                    AgentMsi   = new MsiInstaller(Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Citrix\\XenToolsInstaller", "MSISourceDir", Application.StartupPath) + "citrixguestagentx64.msi");

                    InstallerNSIS = new NSISItem("Citrix XenTools", (string)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Wow6432Node\\Citrix\\XenToolsInstaller", "MSISourceDir", Application.StartupPath));
                }
                else
                {
                    Trace.WriteLine("32 Bit Install");
                    installdir = (string)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Citrix\\XenToolsInstaller", "Install_Dir", Application.StartupPath);
                    DriversMsi = new DriverPackage((string)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Citrix\\XenToolsInstaller", "MSISourceDir", Application.StartupPath), Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Citrix\\XenToolsInstaller", "MSISourceDir", Application.StartupPath) + "citrixxendriversx86.msi");
                    VssProvMsi = new MsiInstaller(Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Citrix\\XenToolsInstaller", "MSISourceDir", Application.StartupPath) + "citrixvssx86.msi");
                    AgentMsi   = new MsiInstaller(Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Citrix\\XenToolsInstaller", "MSISourceDir", Application.StartupPath) + "citrixguestagentx86.msi");

                    InstallerNSIS = new NSISItem("Citrix XenTools", (string)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Citrix\\XenToolsInstaller", "MSISourceDir", Application.StartupPath));
                }
                installdir = "\"" + installdir + "\"";

                VifConfig Vif = new VifConfig();
                Trace.WriteLine("Entering state loop");
                Dictionary <string, int[]> prog = new Dictionary <string, int[]>();

                prog["installscore"]     = new int[] { 300, 0 };
                prog["tempscore"]        = new int[] { 0, 0 };
                InstallState.MaxProgress = prog["installscore"][0];

                if (InstallService.isWOW64())
                {
                    Trace.WriteLine("Install failed");
                    InstallState.Fail("PV Tools cannot be installed on systems where .Net applications are forced to run under WoW64\n\nSet HKEY_LOCAL_MACHINE\\Software\\Microsoft\\.NetFramework\\Enable64Bit to 1 and attempt the install again.");
                }

                while ((!InstallState.Failed) && (InstallState.RebootCount > 0) && (!InstallState.Done))
                {
                    InstallState.Unchanged  = true;
                    prog["installscore"][1] = 0;
                    if (InstallState.GotAgent)
                    {
                        prog["installscore"][1] += 100;
                    }
                    if (InstallState.NsisFree)
                    {
                        prog["installscore"][1] += 100;
                    }
                    if (InstallState.GotDrivers)
                    {
                        prog["installscore"][1] += 100;
                    }
                    InstallState.MaxProgress = prog["installscore"][0] + prog["tempscore"][0];
                    InstallState.Progress    = prog["installscore"][1] + prog["tempscore"][1];

                    if (InstallState.GotAgent &&
                        ((InstallWizard.InstallerState.WinVersion.isServerSKU() && InstallState.GotVssProvider) || !InstallWizard.InstallerState.WinVersion.isServerSKU()) &&
                        InstallState.GotDrivers &&
                        !InstallState.RebootNow &&
                        InstallState.NsisFree &&
                        !InstallState.NeedsReboot)
                    {
                        Trace.WriteLine("Everything is installed");
                        InstallState.Installed = true;
                        InstallState.Done      = true;

                        /* try
                         * {
                         *  // Registry.LocalMachine.OpenSubKey(@"Software").OpenSubKey("Microsoft").OpenSubKey("Windows").OpenSubKey("CurrentVersion").OpenSubKey("Run",true).DeleteValue("CitrixXenAgentInstaller");
                         * }
                         * catch (Exception e){
                         *   Trace.WriteLine("Failed to remove install agent run subkey: " + e.ToString());
                         *   InstallState.Fail("Failed to remove install agent run subkey: " + e.ToString());
                         *   continue;
                         * }*/
                        continue;
                    }



                    if ((!InstallState.GotDrivers) && (InstallState.NsisFree) && (!HWID.needsupdate()))
                    {
                        Trace.WriteLine("Check if drivers are functioning");

                        string oldtext = InstallState.DriverText;

                        if ((DriversMsi.installed() && (!DriversMsi.olderinstalled())) && DriversMsi.functioning(ref InstallState.DriverText))
                        {
                            Trace.WriteLine("Drivers functioning");
                            InstallState.GotDrivers = true;
                        }
                        else
                        {
                            if (InstallState.DriverText != oldtext)
                            {
                                InstallState.PollingReset();
                            }
                            if ((!InstallState.DriversPlaced) && ((!DriversMsi.installed()) || DriversMsi.olderinstalled()))
                            {
                                Trace.WriteLine("Driver install package not found");
                                Trace.WriteLine("Attempt driver install");
                                Trace.WriteLine(DriversMsi.ToString());

                                if (DriversMsi.olderinstalled())
                                {
                                    Vif.CopyNewPVWorkaround();
                                }

                                try
                                {
                                    DriversMsi.install("INSTALLDIR=" + installdir, "driversmsi", InstallState);
                                    InstallState.DriversPlaced = true;
                                    InstallState.NeedsReboot   = true;
                                    InstallState.Polling       = true;
                                    Trace.WriteLine("Install success");
                                    continue;
                                }
                                catch (InstallerException e)
                                {
                                    Trace.WriteLine("Install failed");
                                    InstallState.Fail("Failed to install drivers: " + e.ErrorMessage);
                                    continue;
                                }
                            }
                            else
                            {
                                if ((!InstallState.DriversPlaced) && InstallState.NotRebooted)
                                {
                                    DriversMsi.repair();
                                    Trace.WriteLine("Repair done");
                                    InstallState.DriversPlaced = true;
                                    InstallState.NeedsReboot   = true;
                                    InstallState.Polling       = true;
                                    continue;
                                }
                                else
                                {
                                    Trace.WriteLine("Repair not needed");
                                }
                            }
                            if (!InstallState.RebootNow)
                            {
                                Trace.WriteLine("Wait to see if drivers initialize");
                                int noneedtoreboot = (int)Application.CommonAppDataRegistry.GetValue("DriverFinalReboot", 0);
                                if (noneedtoreboot == 0)
                                {
                                    Trace.WriteLine("Pool - I don't know if I have to reboot");
                                    InstallState.Polling = true;
                                }
                                else
                                {
                                    Trace.WriteLine("Don't poll, I have to reboot");
                                    InstallState.RebootNow = true;
                                }
                            }
                        }
                    }
                    else
                    {
                        Trace.WriteLine("No DriverMSI work");
                    }


                    if ((!InstallState.NsisFree) && (!InstallState.NsisUninstalling))
                    {
                        Trace.WriteLine("Checking NSIS");
                        if (InstallerNSIS.installed())
                        {
                            Trace.WriteLine("NSIS is installed, and needs to be removed");
                            if (InstallState.RebootReady)
                            {
                                Trace.WriteLine("Removing NSIS");
                                Vif.CopyPV();
                                Trace.WriteLine("Attempting NSIS Uninstall");
                                InstallState.NsisUninstalling = true;
                                InstallState.RebootNow        = true;
                            }
                            else
                            {
                                Trace.WriteLine("We'll remove NSIS next reboot");
                                InstallState.RebootNow = true;
                            }
                        }
                        else
                        {
                            Trace.WriteLine("No NSIS based installer found");
                            if (HWID.needsupdate())
                            {
                                Vif.CopyPV();
                                Trace.WriteLine("Attempting legacy Install");
                                try
                                {
                                    RegistryKey classes = Registry.LocalMachine.OpenSubKey(@"System\CurrentControlSet\Control\Class");
                                    foreach (String classuuid in classes.GetSubKeyNames())
                                    {
                                        Trace.WriteLine("Examining " + classuuid);
                                        RegistryKey classkey = classes.OpenSubKey(classuuid, true);
                                        string[]    filters  = (string[])classkey.GetValue("UpperFilters");
                                        if (filters != null)
                                        {
                                            Trace.WriteLine("UpperFilters Exists");
                                            List <string> newfilters = new List <String>();
                                            foreach (String filter in filters)
                                            {
                                                if (filter.ToUpper() != "XENFILT")
                                                {
                                                    newfilters.Add(filter);
                                                }
                                                else
                                                {
                                                    Trace.WriteLine("Removing XENFILT");
                                                }
                                            }
                                            if (newfilters.Count > 0)
                                            {
                                                if (newfilters.Count < filters.Length)
                                                {
                                                    Trace.WriteLine("Updating UpperFilters");
                                                    classkey.SetValue("UpperFilters", newfilters.ToArray(), RegistryValueKind.MultiString);
                                                }
                                            }
                                            else
                                            {
                                                classkey.DeleteValue("UpperFilters");
                                            }
                                        }
                                        else
                                        {
                                            Trace.WriteLine("UpperFilters not found");
                                        }
                                    }
                                }
                                catch
                                {
                                    Trace.WriteLine("Removing xenfilt from UpperFilters entries failed");
                                }
                                if (DriversMsi.installed())
                                {
                                    DriversMsi.uninstall();
                                }
                                if (AgentMsi.installed())
                                {
                                    AgentMsi.uninstall();
                                }

                                InstallState.NsisUninstalling = true;
                                InstallState.RebootNow        = true;
                            }
                            InstallState.NsisFree = true;
                        }
                    }
                    else
                    {
                        Trace.WriteLine("No NSIS work");
                    }

                    if (InstallWizard.InstallerState.WinVersion.isServerSKU())
                    {
                        if ((!InstallState.GotVssProvider) && (InstallState.NsisFree) && (!InstallState.NsisUninstalling))
                        {
                            Trace.WriteLine("Checking Vss Provider");
                            if (!VssProvMsi.installed())
                            {
                                Trace.WriteLine("Vss Provider not found, installing");
                                Trace.WriteLine(VssProvMsi.ToString());
                                try
                                {
                                    VssProvMsi.install("INSTALLDIR=" + installdir, "vssprov1msi", InstallState);
                                }
                                catch (InstallerException e)
                                {
                                    InstallState.Fail("Failed to install Vss  Provider : " + e.ErrorMessage);
                                    continue;
                                }
                            }
                            else if (VssProvMsi.olderinstalled())
                            {
                                Trace.WriteLine("Old Vss Provider found, updating");
                                try
                                {
                                    VssProvMsi.install("INSTALLDIR=" + installdir, "vssprov2msi", InstallState);
                                }
                                catch (InstallerException e)
                                {
                                    InstallState.Fail("Failed to install Vss Provider : " + e.ErrorMessage);
                                    continue;
                                }
                            }
                            else
                            {
                                Trace.WriteLine("Correct Vss Provider found");
                                InstallState.GotVssProvider = true;
                            }
                        }
                        else
                        {
                            Trace.WriteLine("No VSS Work");
                        }
                    }
                    else
                    {
                        Trace.WriteLine("No ServerSKU Work");
                    }

                    if ((!InstallState.GotAgent) && (InstallState.NsisFree) && (!InstallState.NsisUninstalling))
                    {
                        Trace.WriteLine("Checking Agent");
                        if (!AgentMsi.installed())
                        {
                            Trace.WriteLine("Agent not found, installing");
                            Trace.WriteLine(AgentMsi.ToString());
                            try
                            {
                                AgentMsi.install("INSTALLDIR=" + installdir, "agent1msi", InstallState);
                            }
                            catch (InstallerException e)
                            {
                                InstallState.Fail("Failed to install Guest Agent : " + e.ErrorMessage);
                                continue;
                            }
                        }
                        else if (AgentMsi.olderinstalled())
                        {
                            Trace.WriteLine("Old Agent found, updating");
                            try
                            {
                                AgentMsi.install("INSTALLDIR=" + installdir, "agent2msi", InstallState);
                            }
                            catch (InstallerException e)
                            {
                                InstallState.Fail("Failed to install Guest Agent : " + e.ErrorMessage);
                                continue;
                            }
                        }
                        else
                        {
                            Trace.WriteLine("Correct Agent found");
                            InstallState.GotAgent = true;
                        }
                    }
                    else
                    {
                        Trace.WriteLine("No Agent Work");
                    }

                    if (InstallState.Polling)
                    {
                        if (InstallState.PollTimedOut)
                        {
                            Trace.WriteLine("Polling timed out");
                            InstallState.RebootNow   = true;
                            InstallState.NeedsReboot = false;
                            InstallState.Polling     = false;
                        }
                        else
                        {
                            prog["tempscore"][1] += 1;
                            prog["tempscore"][0] += 1;
                            InstallState.Sleep(5000);
                        }
                    }
                    else
                    {
                        Trace.WriteLine("No Polling Work");
                    }

                    if ((!InstallState.RebootReady) && InstallState.RebootNow && InstallState.Unchanged)
                    {
                        // We are ready to reboot
                        Trace.WriteLine("Ready to reboot");
                        InstallState.Polling       = false;
                        InstallState.RebootDesired = true;
                        if (InstallState.WaitForShutdown())
                        {
                            Trace.WriteLine("Shutdown occuring");
                        }
                        continue;
                    }
                    else
                    {
                        Trace.WriteLine("No rebootready work");
                    }

                    if (InstallState.RebootReady && InstallState.RebootNow && InstallState.Unchanged)
                    {
                        Trace.WriteLine("Expecting Reboot /  Shutdown");
                        InstallState.Rebooting = true;
                        if (InstallState.NsisUninstalling)
                        {
                            // We have to do the HWID check before NSIS is uninstalled, but
                            // when we know NSIS is about to be uninstalled.
                            //
                            // NSIS leads to a blue screen if it doesn't have the right HWID at start of day
                            //
                            if ((!InstallState.GotDrivers) && (!InstallState.HWIDCorrect))
                            {
                                Trace.WriteLine("Checking HWID");
                                if (HWID.needsupdate())
                                {
                                    Trace.WriteLine("HWID Needs updating");
                                    try
                                    {
                                        if (!HWID.update())
                                        {
                                            InstallState.Fail("Unable to enable Xeniface WMI Client when trying to change device id");
                                        }
                                        Trace.WriteLine("HWID should be changed following next reboot");
                                    }
                                    catch (ManagementException)
                                    {
                                        //This suggests we don't have a WMI interface.  update nsis and try again
                                        InstallState.NsisUninstalling = false;
                                    }
                                }
                                else
                                {
                                    Trace.WriteLine("Correct HWID Found");
                                    InstallState.HWIDCorrect = true;
                                }
                            }
                            // Irritatingly, the NSIS installer continues running for longer than the
                            // lifetime of the uninstall.exe process.  Since we don't want to reboot
                            // while it (or its unattached children) are still running, we rely on
                            // the NSIS uninstaller to perform its own reboot, when it is done.
                            if (InstallState.NsisUninstalling)
                            {
                                InstallerNSIS.uninstall();
                            }
                            else
                            {
                                //DriverPackage.addcerts(InstallerNSIS.path);
                                InstallerNSIS.update();

                                //NSIS returns the same errorlevel for 'failure to install' and for
                                // 'needs a reboot to install'.  So we have to presume the install
                                // was a success.
                            }
                            InstallState.RebootNow = false;
                            InstallState.Done      = true;
                        }
                        else
                        {
                            InstallState.Done      = true;
                            InstallState.RebootNow = false;
                            InstallState.DoShutdown();
                        }
                    }
                    else
                    {
                        Trace.WriteLine("No Shutdown work");
                    }
                }

                Trace.WriteLine("Exited install cycle " + InstallState.Failed + " " + InstallState.RebootCount + " " + InstallState.Done);

                if (!InstallState.Passive)
                {
                    // We want to wait until the user terminates the GUI installer before shutting down the service
                    InstallState.WaitForDone();
                }

                if (InstallState.Installed || InstallState.Cancelled || InstallState.Failed)
                {
                    Trace.WriteLine("Installed " + InstallState.Installed + " Cancelled " + InstallState.Cancelled + " Failed " + InstallState.Failed);

                    try
                    {
                        Registry.LocalMachine.OpenSubKey(@"Software").OpenSubKey("Microsoft").OpenSubKey("Windows").OpenSubKey("CurrentVersion").OpenSubKey("Run", true).DeleteValue("CitrixXenAgentInstaller");
                    }
                    catch (Exception e)
                    {
                        if (!InstallState.Passive)
                        {
                            Trace.WriteLine("Failed to remove install agent run subkey: " + e.ToString());
                            InstallState.Fail("Failed to remove install agent subkey");
                        }
                    }
                    Trace.WriteLine("Turn off DriverFinalReboot");
                    Application.CommonAppDataRegistry.SetValue("DriverFinalReboot", 0);
                    Registry.SetValue(@"HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\XenPVInstall", "Start", 3);
                    (new Thread(delegate()
                    {
                        this.Stop();
                    })).Start();
                }
            }
            catch (Exception e)
            {
                Trace.WriteLine("Install exception :" + e.ToString());
                InstallState.Fail("Failed to install due to exception" + e.ToString());
                if (!InstallState.Passive)
                {
                    // We want to wait until the user terminates the GUI installer before shutting down the service

                    InstallState.WaitForDone();
                }
                try
                {
                    Registry.LocalMachine.OpenSubKey(@"Software").OpenSubKey("Microsoft").OpenSubKey("Windows").OpenSubKey("CurrentVersion").OpenSubKey("Run", true).DeleteValue("CitrixXenAgentInstaller");
                }
                catch {
                    Trace.WriteLine("Failed to remove install agent run subkey (error state)");
                    InstallState.Fail("Failed to remove install agent subkey");
                }
            }
        }
Esempio n. 10
0
 public void LoadMsi()
 {
     msiInterface = new MsiInstaller("test.msi");
 }