protected override void ProcessRecord()
        {
            ProviderInfo provider;
            PSDriveInfo  drive;
            var          psPath = SessionState.Path.GetUnresolvedProviderPathFromPSPath(UnattendFile, out provider, out drive);

            var details = ServiceControlInstanceMetadata.Load(psPath);

            details.ServiceAccount    = ServiceAccount;
            details.ServiceAccountPwd = Password;
            var zipfolder = Path.GetDirectoryName(MyInvocation.MyCommand.Module.Path);
            var logger    = new PSLogger(Host);
            var installer = new UnattendInstaller(logger, zipfolder);

            try
            {
                logger.Info("Installing Service Control instance...");
                if (installer.Add(details, PromptToProceed))
                {
                    var instance = ServiceControlInstance.FindByName(details.Name);
                    if (instance != null)
                    {
                        WriteObject(PsServiceControl.FromInstance(instance));
                    }
                    else
                    {
                        throw new Exception("Unknown error creating instance");
                    }
                }
            }
            catch (Exception ex)
            {
                ThrowTerminatingError(new ErrorRecord(ex, null, ErrorCategory.NotSpecified, null));
            }
        }
        public void ChangeConfigTests()
        {
            var logger    = new TestLogger();
            var installer = new UnattendInstaller(logger, deploymentCache);

            logger.Info("Deleting instances");
            DeleteInstance();

            logger.Info("Removing the test queue instances");
            RemoveAltMSMQQueues();

            logger.Info("Recreating the MSMQ instance");
            CreateInstanceMSMQ();

            logger.Info("Changing the URLACL");
            var msmqTestInstance = ServiceControlInstance.Instances().First(p => p.Name.Equals("Test.ServiceControl.MSMQ", StringComparison.OrdinalIgnoreCase));

            msmqTestInstance.HostName = Environment.MachineName;
            msmqTestInstance.Port     = 33338;
            installer.Update(msmqTestInstance, true);
            Assert.IsTrue(msmqTestInstance.Service.Status == ServiceControllerStatus.Running, "Update URL change failed");

            logger.Info("Changing LogPath");
            msmqTestInstance         = ServiceControlInstance.Instances().First(p => p.Name.Equals("Test.ServiceControl.MSMQ", StringComparison.OrdinalIgnoreCase));
            msmqTestInstance.LogPath = @"c:\temp\testloggingchange";
            installer.Update(msmqTestInstance, true);
            Assert.IsTrue(msmqTestInstance.Service.Status == ServiceControllerStatus.Running, "Update Logging changed failed");

            logger.Info("Updating Queue paths");
            msmqTestInstance            = ServiceControlInstance.Instances().First(p => p.Name.Equals("Test.ServiceControl.MSMQ", StringComparison.OrdinalIgnoreCase));
            msmqTestInstance.AuditQueue = "alternateAudit";
            msmqTestInstance.ErrorQueue = "alternateError";
            installer.Update(msmqTestInstance, true);
            Assert.IsTrue(msmqTestInstance.Service.Status == ServiceControllerStatus.Running, "Update Queues changed failed");
        }
        public void CreateInstanceMSMQ()
        {
            var installer    = new UnattendInstaller(new TestLogger(), deploymentCache);
            var instanceName = "Test.ServiceControl.Msmq";
            var root         = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), @"Test", instanceName);
            var details      = new ServiceControlInstanceMetadata
            {
                DisplayName          = instanceName.Replace(".", " "),
                Name                 = instanceName,
                ServiceDescription   = "Test SC Instance",
                DBPath               = Path.Combine(root, "Database"),
                LogPath              = Path.Combine(root, "Logs"),
                InstallPath          = Path.Combine(root, "Binaries"),
                HostName             = "localhost",
                Port                 = 33335,
                VirtualDirectory     = null,
                AuditLogQueue        = "audit.log",
                AuditQueue           = "audit",
                ForwardAuditMessages = false,
                ErrorQueue           = "error",
                ErrorLogQueue        = "error.log",
                TransportPackage     = "MSMQ",
                ReportCard           = new ReportCard()
            };

            details.Validate(s => false);
            if (details.ReportCard.HasErrors)
            {
                throw new Exception($"Validation errors:  {string.Join("\r\n", details.ReportCard.Errors)}");
            }
            Assert.DoesNotThrow(() => installer.Add(details, s => false));
        }
        public void DeleteInstance()
        {
            var installer = new UnattendInstaller(new TestLogger(), deploymentCache);

            foreach (var instance in ServiceControlInstance.Instances().Where(p => p.Name.StartsWith("Test.ServiceControl", StringComparison.OrdinalIgnoreCase)))
            {
                installer.Delete(instance.Name, true, true);
            }
        }
        protected override void ProcessRecord()
        {
            var logger = new PSLogger(Host);

            var zipFolder = Path.GetDirectoryName(MyInvocation.MyCommand.Module.Path);
            var installer = new UnattendInstaller(logger, zipFolder);

            foreach (var name in Name)
            {
                var options = new InstanceUpgradeOptions {
                    AuditRetentionPeriod = AuditRetentionPeriod, ErrorRetentionPeriod = ErrorRetentionPeriod, OverrideEnableErrorForwarding = ForwardErrorMessages
                };
                var instance = ServiceControlInstance.FindByName(name);
                if (instance == null)
                {
                    WriteWarning($"No action taken. An instance called {name} was not found");
                    break;
                }

                options.OverrideEnableErrorForwarding = ForwardErrorMessages;


                // Migrate Value
                if (!options.AuditRetentionPeriod.HasValue)
                {
                    if (instance.AppSettingExists(SettingsList.HoursToKeepMessagesBeforeExpiring.Name))
                    {
                        var i = instance.ReadAppSetting(SettingsList.HoursToKeepMessagesBeforeExpiring.Name, -1);
                        if (i != -1)
                        {
                            options.AuditRetentionPeriod = TimeSpan.FromHours(i);
                        }
                    }
                }

                if (!options.OverrideEnableErrorForwarding.HasValue & !instance.AppSettingExists(SettingsList.ForwardErrorMessages.Name))
                {
                    ThrowTerminatingError(new ErrorRecord(new Exception($"Upgrade of {instance.Name} aborted. ForwardErrorMessages parameter must be set to true or false because the configuration file has no setting for ForwardErrorMessages. This setting is mandatory as of version 1.12"), "UpgradeFailure", ErrorCategory.InvalidArgument, null));
                }

                if (!options.ErrorRetentionPeriod.HasValue & !instance.AppSettingExists(SettingsList.ErrorRetentionPeriod.Name))
                {
                    ThrowTerminatingError(new ErrorRecord(new Exception($"Upgrade of {instance.Name} aborted. ErrorRetentionPeriod parameter must be set to timespan because the configuration file has no setting for ErrorRetentionPeriod. This setting is mandatory as of version 1.13"), "UpgradeFailure", ErrorCategory.InvalidArgument, null));
                }

                if (!options.AuditRetentionPeriod.HasValue & !instance.AppSettingExists(SettingsList.AuditRetentionPeriod.Name))
                {
                    ThrowTerminatingError(new ErrorRecord(new Exception($"Upgrade of {instance.Name} aborted. AuditRetentionPeriod parameter must be set to timespan because the configuration file has no setting for AuditRetentionPeriod. This setting is mandatory as of version 1.13"), "UpgradeFailure", ErrorCategory.InvalidArgument, null));
                }

                if (!installer.Upgrade(instance, options))
                {
                    ThrowTerminatingError(new ErrorRecord(new Exception($"Upgrade of {instance.Name} failed"), "UpgradeFailure", ErrorCategory.InvalidResult, null));
                }
            }
        }
        public void UpgradeInstance()
        {
            var installer = new UnattendInstaller(new TestLogger(), deploymentCache);

            foreach (var instance in ServiceControlInstance.Instances())  //.Where(p => p.Name.StartsWith("Test.ServiceControl", StringComparison.OrdinalIgnoreCase)))
            {
                installer.Upgrade(instance, new InstanceUpgradeOptions {
                    AuditRetentionPeriod = TimeSpan.FromDays(30), ErrorRetentionPeriod = TimeSpan.FromDays(15), OverrideEnableErrorForwarding = true
                });
            }
        }
Example #7
0
        protected override void ProcessRecord()
        {
            var details = new ServiceControlInstanceMetadata
            {
                InstallPath          = InstallPath,
                LogPath              = LogPath,
                DBPath               = DBPath,
                Name                 = Name,
                DisplayName          = string.IsNullOrWhiteSpace(DisplayName) ? Name : DisplayName,
                ServiceDescription   = Description,
                ServiceAccount       = ServiceAccount,
                ServiceAccountPwd    = ServiceAccountPassword,
                HostName             = HostName,
                Port                 = Port,
                VirtualDirectory     = VirtualDirectory,
                AuditQueue           = AuditQueue,
                ErrorQueue           = ErrorQueue,
                AuditLogQueue        = string.IsNullOrWhiteSpace(AuditLogQueue) ? null : AuditLogQueue,
                ErrorLogQueue        = string.IsNullOrWhiteSpace(ErrorLogQueue) ? null : ErrorLogQueue,
                ForwardAuditMessages = ForwardAuditMessages.ToBool(),
                ForwardErrorMessages = ForwardErrorMessages.ToBool(),
                AuditRetentionPeriod = AuditRetentionPeriod,
                ErrorRetentionPeriod = ErrorRetentionPeriod,
                ConnectionString     = ConnectionString,
                TransportPackage     = Transport
            };

            var zipfolder = Path.GetDirectoryName(MyInvocation.MyCommand.Module.Path);
            var logger    = new PSLogger(Host);

            var installer = new UnattendInstaller(logger, zipfolder);

            try
            {
                logger.Info("Installing Service Control instance...");
                if (installer.Add(details, PromptToProceed))
                {
                    var instance = ServiceControlInstance.FindByName(details.Name);
                    if (instance != null)
                    {
                        WriteObject(PsServiceControl.FromInstance(instance));
                    }
                    else
                    {
                        throw new Exception("Unknown error creating instance");
                    }
                }
            }
            catch (Exception ex)
            {
                ThrowTerminatingError(new ErrorRecord(ex, null, ErrorCategory.NotSpecified, null));
            }
        }
        protected override void ProcessRecord()
        {
            var logger    = new PSLogger(Host);
            var zipfolder = Path.GetDirectoryName(MyInvocation.MyCommand.Module.Path);
            var installer = new UnattendInstaller(logger, zipfolder);

            foreach (var name in Name)
            {
                var instance = ServiceControlInstance.FindByName(name);
                if (instance == null)
                {
                    WriteWarning($"No action taken. An instance called {name} was not found");
                    break;
                }
                WriteObject(installer.Delete(instance.Name, RemoveDB.ToBool(), RemoveLogs.ToBool()));
            }
        }
        public static ActionResult ServiceControlUnattendedInstall(Session session)
        {
            var logger = new MSILogger(session);

            var unattendedInstaller = new UnattendInstaller(logger, session["APPDIR"]);
            var zipInfo             = ServiceControlZipInfo.Find(session["APPDIR"] ?? ".");

            if (!zipInfo.Present)
            {
                logger.Error("Zip file not found. Service Control service instances can not be upgraded or installed");
                return(ActionResult.Failure);
            }

            UpgradeInstances(session, zipInfo, logger, unattendedInstaller);
            UnattendedInstall(session, logger, unattendedInstaller);
            ImportLicenseInstall(session, logger);
            return(ActionResult.Success);
        }
Example #10
0
        public static ActionResult ServiceControlUnattendedRemoval(Session session)
        {
            var logger = new MSILogger(session);
            var removeInstancesPropertyValue = session["REMOVEALLINSTANCESANDDATA"];

            if (string.IsNullOrWhiteSpace(removeInstancesPropertyValue))
            {
                return(ActionResult.NotExecuted);
            }

            switch (removeInstancesPropertyValue.ToUpper())
            {
            case "YES":
            case "TRUE":
                break;

            default:
                return(ActionResult.NotExecuted);
            }

            if (ServiceControlInstance.Instances().Count == 0)
            {
                return(ActionResult.Success);
            }

            var unattendedInstaller = new UnattendInstaller(logger, session["APPDIR"]);

            foreach (var instance in ServiceControlInstance.Instances())
            {
                try
                {
                    unattendedInstaller.Delete(instance.Name, true, true);
                }
                catch (Exception ex)
                {
                    logger.Error($"Error thrown when removing instance {instance.Name} - {ex}");
                }
            }
            return(ActionResult.Success);
        }
        static void UnattendedInstall(Session session, MSILogger logger, UnattendInstaller unattendedInstaller)
        {
            logger.Info("Checking for unattended file");

            var unattendedFilePropertyValue = session["UNATTENDEDFILE"];

            if (string.IsNullOrWhiteSpace(unattendedFilePropertyValue))
            {
                return;
            }

            var serviceAccount = session["SERVICEACCOUNT"];
            var password       = session["PASSWORD"];

            logger.Info($"UNATTENDEDFILE: {unattendedFilePropertyValue}");
            var currentDirectory   = session["CURRENTDIRECTORY"];
            var unattendedFilePath = Environment.ExpandEnvironmentVariables(Path.IsPathRooted(unattendedFilePropertyValue) ? unattendedFilePropertyValue : Path.Combine(currentDirectory, unattendedFilePropertyValue));

            logger.Info($"Expanded unattended filepath to : {unattendedFilePropertyValue}");

            if (File.Exists(unattendedFilePath))
            {
                logger.Info($"File Exists : {unattendedFilePropertyValue}");
                var instanceToInstallDetails = ServiceControlInstanceMetadata.Load(unattendedFilePath);

                if (!string.IsNullOrWhiteSpace(serviceAccount))
                {
                    instanceToInstallDetails.ServiceAccount    = serviceAccount;
                    instanceToInstallDetails.ServiceAccountPwd = password;
                }
                unattendedInstaller.Add(instanceToInstallDetails, s => false);
            }
            else
            {
                logger.Error($"The specified unattended install file was not found : '{unattendedFilePath}'");
            }
        }
        static void UpgradeInstances(Session session, ServiceControlZipInfo zipInfo, MSILogger logger, UnattendInstaller unattendedInstaller)
        {
            var options = new InstanceUpgradeOptions();

            var upgradeInstancesPropertyValue = session["UPGRADEINSTANCES"];

            if (string.IsNullOrWhiteSpace(upgradeInstancesPropertyValue))
            {
                return;
            }
            upgradeInstancesPropertyValue = upgradeInstancesPropertyValue.Trim();

            var forwardErrorMessagesPropertyValue = session["FORWARDERRORMESSAGES"];

            try
            {
                options.OverrideEnableErrorForwarding = bool.Parse(forwardErrorMessagesPropertyValue);
            }
            catch
            {
                options.OverrideEnableErrorForwarding = null;
            }

            var auditRetentionPeriodPropertyValue = session["AUDITRETENTIONPERIOD"];

            try
            {
                options.AuditRetentionPeriod = TimeSpan.Parse(auditRetentionPeriodPropertyValue);
            }
            catch
            {
                options.AuditRetentionPeriod = null;
            }

            var errorRetentionPeriodPropertyValue = session["ERRORRETENTIONPERIOD"];

            try
            {
                options.ErrorRetentionPeriod = TimeSpan.Parse(errorRetentionPeriodPropertyValue);
            }
            catch
            {
                options.ErrorRetentionPeriod = null;
            }

            //determine what to upgrade
            var instancesToUpgrade = new List <ServiceControlInstance>();

            if (upgradeInstancesPropertyValue.Equals("*", StringComparison.OrdinalIgnoreCase) || upgradeInstancesPropertyValue.Equals("ALL", StringComparison.OrdinalIgnoreCase))
            {
                instancesToUpgrade.AddRange(ServiceControlInstance.Instances());
            }
            else
            {
                var candidates = upgradeInstancesPropertyValue.Replace(" ", String.Empty).Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                instancesToUpgrade.AddRange(ServiceControlInstance.Instances().Where(instance => candidates.Contains(instance.Name, StringComparer.OrdinalIgnoreCase)));
            }

            // do upgrades
            foreach (var instance in instancesToUpgrade)
            {
                if (zipInfo.Version > instance.Version)
                {
                    if (!instance.AppSettingExists(SettingsList.ForwardErrorMessages.Name) & !options.OverrideEnableErrorForwarding.Value)
                    {
                        logger.Warn($"Unattend upgrade {instance.Name} to {zipInfo.Version} not attempted. FORWARDERRORMESSAGES MSI parameter was required because appsettings needed a value for '{SettingsList.ForwardErrorMessages.Name}'");
                        continue;
                    }


                    if (!options.AuditRetentionPeriod.HasValue)
                    {
                        if (!instance.AppSettingExists(SettingsList.AuditRetentionPeriod.Name))
                        {
                            //Try migration first
                            if (instance.AppSettingExists(SettingsList.HoursToKeepMessagesBeforeExpiring.Name))
                            {
                                var i = instance.ReadAppSetting(SettingsList.HoursToKeepMessagesBeforeExpiring.Name, -1);
                                if (i > 0)
                                {
                                    options.AuditRetentionPeriod = TimeSpan.FromHours(i);
                                }
                            }
                            else
                            {
                                logger.Warn($"Unattend upgrade {instance.Name} to {zipInfo.Version} not attempted. AUDITRETENTIONPERIOD MSI parameter was required because appsettings needed a value for '{SettingsList.AuditRetentionPeriod.Name}'");
                                continue;
                            }
                        }
                    }

                    if (!instance.AppSettingExists(SettingsList.ErrorRetentionPeriod.Name) & !options.ErrorRetentionPeriod.HasValue)
                    {
                        logger.Warn($"Unattend upgrade {instance.Name} to {zipInfo.Version} not attempted. ERRORRETENTIONPERIOD MSI parameter was required because appsettings needed a value for '{SettingsList.ErrorRetentionPeriod.Name}'");
                        continue;
                    }

                    if (!unattendedInstaller.Upgrade(instance, options))
                    {
                        logger.Warn($"Failed to upgrade {instance.Name} to {zipInfo.Version}");
                    }
                }
            }
        }