private static int StartIfPossible( CommandlineOptions arg1, Shell arg2) { var svc = new WindowsServiceUtil(arg2.ServiceName); if (svc.State == ServiceState.Unknown || svc.State == ServiceState.NotFound) { return(Fail($"{svc.ServiceName} not installed or not queryable")); } var entryExe = new Uri(Assembly.GetEntryAssembly()?.Location ?? "").LocalPath; if (!entryExe.Equals(svc.Commandline, StringComparison.InvariantCultureIgnoreCase)) { return(Fail( $"{svc.ServiceName} is installed at {svc.Commandline}.", "Issuing start command here will probably not do what you expect." )); } return(Starters.TryGetValue(svc.State, out var handler) ? handler(svc) : Fail($"No handler found for service state {svc.State}")); }
#pragma warning disable S3241 // Methods should not return values that are never used private int StopMe(bool silentFail = false) #pragma warning restore S3241 // Methods should not return values that are never used { var existingServiceUtil = new WindowsServiceUtil(ServiceName); if (!existingServiceUtil.IsInstalled) { return(FailWith("Unable to stop service: not installed", silentFail)); } if (!existingServiceUtil.IsStoppable) { return(FailWith("Service already stopped", silentFail)); } try { existingServiceUtil.Start(); return((int)CommandlineOptions.ExitCodes.Success); } catch (Exception ex) { return(FailWith("Unable to start service: " + ex.Message, silentFail)); } }
private int StartMe() { var existingServiceUtil = new WindowsServiceUtil(ServiceName); if (!existingServiceUtil.IsInstalled) { Console.WriteLine("Unable to start service: not installed"); return((int)CommandlineOptions.ExitCodes.Failure); } if (!IsStartable(existingServiceUtil)) { Console.WriteLine("Service cannot be started"); return((int)CommandlineOptions.ExitCodes.Failure); } try { existingServiceUtil.Start(); return((int)CommandlineOptions.ExitCodes.Success); } catch (Exception ex) { Console.WriteLine("Unable to start service: " + ex.Message); return((int)CommandlineOptions.ExitCodes.Failure); } }
public void InstallThing() { //---------------Set up test pack------------------- var localPath = TestServicePath; //---------------Assert Precondition---------------- Expect(localPath) .To.Exist($"Expected to find test service at {localPath}"); //---------------Execute Test ---------------------- Run(localPath, "-i"); var util = new WindowsServiceUtil("test service"); Expect(util.IsInstalled).To.Be.True(); // check that we can uninstall util.Uninstall(true); Expect(util.IsInstalled) .To.Be.False(); // check that attempting again throws Expect(() => util.Uninstall(true)) .To.Throw <ServiceNotInstalledException>(); //---------------Test Result ----------------------- }
private void btnInstall_Click(object sender, EventArgs e) { if (WindowsServiceUtil.IsExist(serviceName)) { WindowsServiceUtil.UninstallService(serviceFilePath); } WindowsServiceUtil.InstallService(serviceFilePath); }
public void ServiceExeShouldReturnServiceExe() { // Arrange var service = new WindowsServiceUtil("MYSQL57"); // Act var result = service.Commandline; // Assert }
private void btnStop_Click(object sender, EventArgs e) { if (!WindowsServiceUtil.IsExist(serviceName)) { MessageBox.Show(serviceName + "服务不存在"); } WindowsServiceUtil.ServiceStop(serviceName); }
private void btnUninstall_Click(object sender, EventArgs e) { if (!WindowsServiceUtil.IsExist(serviceName)) { MessageBox.Show(serviceName + "服务不存在"); } WindowsServiceUtil.ServiceStop(serviceName); WindowsServiceUtil.UninstallService(serviceFilePath); }
public void ShouldNotBorkWhenNoService() { //---------------Set up test pack------------------- //---------------Assert Precondition---------------- var svc = new WindowsServiceUtil(RandomValueGen.GetRandomString(20, 30)); //---------------Execute Test ---------------------- Assert.IsFalse(svc.IsInstalled); //---------------Test Result ----------------------- }
private static int StartService(WindowsServiceUtil arg) { try { arg.Start(true); return(Success()); } catch (Exception ex) { return(Fail($"Unable to start {arg.ServiceName}: {ex.Message}")); } }
public void ShouldBeAbleToFindServiceWhenNotRunning() { // Arrange var svc = new WindowsServiceUtil("mysql57"); svc.Stop(); // Act var path = MySqlWindowsServiceFinder.FindPathToMySql(); // Assert Expect(path).Not.To.Be.Null.Or.Empty(); }
public AsimovTask GetUninstallTask() { return(new PowershellUninstallTask( Installable, this, new Dictionary <string, object>() { { "ServiceName", ServiceName } }) { TargetPath = WindowsServiceUtil.GetWindowsServicePath(ServiceName) }); }
public void ReinstallThing() { //---------------Set up test pack------------------- var util = new WindowsServiceUtil("test-service"); //---------------Assert Precondition---------------- Assert.IsTrue(util.IsInstalled); //---------------Execute Test ---------------------- util.Uninstall(true); //---------------Test Result ----------------------- }
public ServiceWrapper( ServiceWrapperConfig config, IDateTimeProvider dateTimeProvider, ILog logger ) { Validate(config); _dateTimeProvider = dateTimeProvider; _logger = logger; _backoff = config.BackoffSeconds; _resetTime = config.ResetAfterSeconds; Name = config.Name; _util = new WindowsServiceUtil(config.Name); }
public void ServiceExe_ShouldReturnPathTo() { //---------------Set up test pack------------------- var util = new WindowsServiceUtil("Themes"); //---------------Assert Precondition---------------- Assert.IsTrue(util.IsInstalled); //---------------Execute Test ---------------------- var path = util.ServiceExe; //---------------Test Result ----------------------- Assert.IsNotNull(path); Assert.AreEqual("c:\\windows\\system32\\svchost.exe -k netsvcs", path.ToLower()); }
private bool IsStoppable(WindowsServiceUtil service) { switch (service.State) { case ServiceState.ContinuePending: case ServiceState.PausePending: case ServiceState.Paused: case ServiceState.Running: case ServiceState.StartPending: return(true); default: return(false); } }
public void ACCEPT_WhenTestingStartupStateOfKnownServices_ShouldReturnExpectedState() { //---------------Set up test pack------------------- //---------------Assert Precondition---------------- //---------------Execute Test ---------------------- var svc1 = new WindowsServiceUtil("mssqlserver"); Assert.AreEqual(ServiceStartupTypes.Automatic, svc1.StartupType); var svc2 = new WindowsServiceUtil("gupdatem"); Assert.AreEqual(ServiceStartupTypes.Manual, svc2.StartupType); //---------------Test Result ----------------------- }
private string QueryForMySqld() { var mysqlService = ServiceController.GetServices() .FirstOrDefault(s => s.ServiceName.ToLower().Contains("mysql")); if (mysqlService == null) { throw _noMySqlInstalledException; } var util = new WindowsServiceUtil(mysqlService.ServiceName); if (!util.IsInstalled) { throw _noMySqlInstalledException; } return(FindServiceExecutablePartIn(util.ServiceExe)); }
public void ServiceExe_ShouldReturnPathTo() { //---------------Set up test pack------------------- var util = new WindowsServiceUtil("Themes"); //---------------Assert Precondition---------------- Expect(util.IsInstalled) .To.Be.True(); //---------------Execute Test ---------------------- var path = util.ServiceExe; //---------------Test Result ----------------------- Expect( path?.ToLowerInvariant() ).To.Equal("c:\\windows\\system32\\svchost.exe -k netsvcs"); }
public void InstallThing() { //---------------Set up test pack------------------- var localPath = TestServicePath; //---------------Assert Precondition---------------- Expect(localPath) .To.Exist($"Expected to find test service at {localPath}"); //---------------Execute Test ---------------------- Run(localPath, "-i"); var util = new WindowsServiceUtil("test service"); Expect(util.IsInstalled).To.Be.True(); //---------------Test Result ----------------------- }
public void ShouldBeAbleToInstallServiceAsDisabled(string arg) { // Arrange var serviceExe = TestServicePath; Expect(serviceExe) .To.Exist($"Expected to find test service at {serviceExe}"); EnsureTestServiceIsNotInstalled(); // Act Do("Install via cli: manual start", () => Run(serviceExe, "-i", arg, "-n", TestServiceName) ); var util = new WindowsServiceUtil(TestServiceName); // Assert Expect(util.StartupType) .To.Equal(ServiceStartupTypes.Disabled); }
public void Execute(DeployContext context) { var deployUnit = (WindowsServiceDeployUnit)context.DeployUnit; using (var controller = new ServiceController(deployUnit.ServiceName)) { StopService(context, controller); context.PhysicalPath = WindowsServiceUtil.GetWindowsServicePath(deployUnit.ServiceName); CleanPhysicalPath(context); CopyNewFiles(context); context.Log.InfoFormat("Starting service {0}", deployUnit.ServiceName); controller.Start(); controller.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromMinutes(1)); } }
private int UninstallMe() { var svcUtil = new WindowsServiceUtil(ServiceName); if (!svcUtil.IsInstalled) { Console.WriteLine("Not installed!"); return((int)CommandlineOptions.ExitCodes.UninstallFailed); } try { svcUtil.Uninstall(); Console.WriteLine("Uninstalled!"); return((int)CommandlineOptions.ExitCodes.Success); } catch (Exception ex) { Console.WriteLine("Unable to install: " + ex.Message); return((int)CommandlineOptions.ExitCodes.UninstallFailed); } }
private int InstallMe(CommandlineOptions cli) { var myExePath = new FileInfo(Environment.GetCommandLineArgs()[0]).FullName; var existingSvcUtil = new WindowsServiceUtil(ServiceName); if (existingSvcUtil.Commandline == myExePath) { Console.WriteLine("Service already installed correctly"); return((int)CommandlineOptions.ExitCodes.Success); } try { if (existingSvcUtil.IsInstalled) { existingSvcUtil.Uninstall(true); } } catch (Exception ex) { Console.WriteLine("Service already installed at: " + existingSvcUtil.Commandline + " and I can't uninstall it: " + ex.Message); return((int)CommandlineOptions.ExitCodes.InstallFailed); } var svcUtil = new WindowsServiceUtil(ServiceName, DisplayName, myExePath); try { var bootFlag = ResolveBootFlagFor(cli); svcUtil.Install(bootFlag); Console.WriteLine("Installed!"); return((int)CommandlineOptions.ExitCodes.Success); } catch (Exception ex) { Console.WriteLine("Unable to install: " + ex.Message); return((int)CommandlineOptions.ExitCodes.InstallFailed); } }
public void Execute(DeployContext context) { var deployUnit = (WindowsServiceDeployUnit)context.DeployUnit; using (var controller = new ServiceController(deployUnit.ServiceName)) { StopService(context, controller); context.PhysicalPath = WindowsServiceUtil.GetWindowsServicePath(deployUnit.ServiceName); CleanPhysicalPath(context); CopyNewFiles(context); context.Log.InfoFormat("Starting service {0}", deployUnit.ServiceName); try { controller.Start(); } catch (InvalidOperationException invalidOpEx) { var win32Exception = invalidOpEx.InnerException as Win32Exception; if (win32Exception != null && win32Exception.NativeErrorCode == ERROR_SERVICE_ALREADY_RUNNING) { context.Log.InfoFormat("Service {0} was already running. Continuing.", deployUnit.ServiceName); } else { throw; } } if (!context.ParameterValues.HasValue("SkipWaitForServiceStart", true)) { controller.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromMinutes(1)); } } }
public void should_return_service_executable_for_path_not_starting_with_double_quote() { var serviceExe = WindowsServiceUtil.GetServiceExecutable(@"C:\temp\service.exe -arg value"); serviceExe.ShouldBe(@"C:\temp\service.exe"); }
public void BigHairyIntegrationTest() { // Arrange var serviceExe = TestServicePath; Expect(serviceExe).To.Exist($"Expected to find test service at {serviceExe}"); EnsureTestServiceIsNotInstalled(); // Act Do("Install via cli", () => Run(serviceExe, "-i", "-n", TestServiceName)); var util = new WindowsServiceUtil(TestServiceName); Do("Test is installed", () => Expect(util.IsInstalled) .To.Be.True() ); Do("Test service executable path", () => Expect(util.ServiceExe) .To.Equal(serviceExe) ); Do("Test default startup type", () => Expect(util.StartupType) .To.Equal(ServiceStartupTypes.Automatic) ); Do("Disabled service", () => { util.Disable(); Expect(util.StartupType) .To.Equal(ServiceStartupTypes.Disabled); }); Do("Re-enable service", () => { util.SetAutomaticStart(); Expect(util.StartupType) .To.Equal(ServiceStartupTypes.Automatic); }); Process process = null; Do("Start service", () => { util.Start(); Expect(util.State) .To.Equal(ServiceState.Running); process = Process.GetProcesses().FirstOrDefault(p => { try { return(p?.MainModule?.FileName.Equals(serviceExe, StringComparison.OrdinalIgnoreCase) ?? false); } catch { return(false); } }); Expect(process).Not.To.Be.Null($"Service should be running: {serviceExe}"); Expect(process.Id) .To.Equal(util.ServicePID); }); var byPath = WindowsServiceUtil.GetServiceByPath(serviceExe); Expect(byPath) .Not.To.Be.Null($"Should be able to query service by path {serviceExe}"); Do("Pause service", () => { byPath.Pause(); Expect(byPath.State) .To.Equal(ServiceState.Paused); }); Do("Resume service", () => { byPath.Continue(); Expect(byPath.State) .To.Equal(ServiceState.Running); }); Do("Stop service", () => { util.Stop(); Expect(util.State) .To.Equal(ServiceState.Stopped); }); Do("Uninstall via cli", () => { Run(serviceExe, "-u", "-n", TestServiceName); Expect(util.IsInstalled) .To.Be.False(); }); Do("Install and start (api)", () => { util.InstallAndStart(); Expect(util.IsInstalled) .To.Be.True(); Expect(util.State) .To.Equal(ServiceState.Running); }); // Do("Uninstall (api)", () => util.Uninstall()); // Assert }
public void BigHairyIntegrationTest() { if (Platform.Is32Bit) { Assert.Ignore( "Running 32-bit: test will fail: 32-bit process cannot access 64-bit process info" ); } // Arrange var serviceExe = TestServicePath; Expect(serviceExe).To.Exist($"Expected to find test service at {serviceExe}"); EnsureTestServiceIsNotInstalled(); // Act Do("Install via cli", () => Run(serviceExe, "-i", "-n", TestServiceName)); var util = new WindowsServiceUtil(TestServiceName); Do("Test is installed", () => Expect(util.IsInstalled) .To.Be.True() ); Do("Test service commandline", () => Expect(util.Commandline) .To.Equal(serviceExe) ); Do("Test default startup type", () => Expect(util.StartupType) .To.Equal(ServiceStartupTypes.Automatic) ); Do("Disabled service", () => { util.Disable(); Expect(util.StartupType) .To.Equal(ServiceStartupTypes.Disabled); }); Do("Re-enable service", () => { util.SetAutomaticStart(); Expect(util.StartupType) .To.Equal(ServiceStartupTypes.Automatic); }); Do("Start service", () => { util.Start(); Expect(util.State) .To.Equal(ServiceState.Running); var processes = Process.GetProcesses(); var process = processes.FirstOrDefault(p => { try { return(p?.MainModule?.FileName.Equals(serviceExe, StringComparison.OrdinalIgnoreCase) ?? false); } catch { return(false); } }); Expect(process).Not.To.Be.Null( () => $"@Service should be running: {serviceExe}\nrunning:\n{DumpProcesses()}" ); Expect(process.Id) .To.Equal(util.ServicePID); string DumpProcesses() { return(processes.Select(p => { try { return $"{p.MainModule.FileName}"; } catch (Exception e) { return $"(unknown) ({e.Message})"; } }).OrderBy(s => s).JoinWith("\n")); ; } }); var byPath = WindowsServiceUtil.GetServiceByPath(serviceExe); Expect(byPath) .Not.To.Be.Null($"Should be able to query service by path {serviceExe}"); Do("Pause service", () => { byPath.Pause(); Expect(byPath.State) .To.Equal(ServiceState.Paused); }); Do("Resume service", () => { byPath.Continue(); Expect(byPath.State) .To.Equal(ServiceState.Running); }); Do("Stop service", () => { util.Stop(); Expect(util.State) .To.Equal(ServiceState.Stopped); }); Do("Uninstall via cli", () => { Run(serviceExe, "-u", "-n", TestServiceName); Expect(util.IsInstalled) .To.Be.False(); }); Do("Install and start (api)", () => { util = new WindowsServiceUtil( TestServiceName, TestServiceName, serviceExe); util.InstallAndStart(); Expect(util.IsInstalled) .To.Be.True(); Expect(util.State) .To.Equal(ServiceState.Running); }); Do("Re-install and start (api)", () => { util = new WindowsServiceUtil( TestServiceName, TestServiceName, serviceExe); util.Uninstall(); util.InstallAndStart(); Expect(util.IsInstalled) .To.Be.True(); Expect(util.State) .To.Equal(ServiceState.Running); }); Do("Uninstall (api)", () => util.Uninstall()); // Assert }
public void ServiceWithArgs() { // Arrange var myPath = new Uri(GetType().Assembly.Location).LocalPath; var myDir = Path.GetDirectoryName(myPath); var serviceExe = Path.Combine(myDir, "ServiceWithArgs.exe"); var logFile = Path.Combine(myDir, "service.log"); var arg1 = GetRandomString(3); var arg2 = GetRandomString(3); var args = new[] { logFile, arg1, arg2 }.Select(p => p.QuoteIfSpaced()); var serviceName = "test-service-foo-bar"; var displayName = "Test Service - Foo,Bar"; var commandline = string.Join( " ", new[] { serviceExe } .Concat(args) ); var util = new WindowsServiceUtil( serviceName, displayName, commandline ); if (util.IsInstalled) { util.Uninstall(); } if (File.Exists(logFile)) { File.Delete(logFile); } // Act using var resetter = new AutoResetter( () => util.Install(), () => util.Uninstall(true)); util.Install(); // Assert Expect(util.IsInstalled) .To.Be.True(); util.Start(); Expect(util.State) .To.Equal(ServiceState.Running); Expect(logFile) .To.Exist(); var logData = TryReadAllLinesFrom(logFile); Expect(logData) .Not.To.Be.Empty(); Expect(logData[0]) .To.Contain(arg1) .Then(arg2); util.Stop(); Expect(util.State) .To.Equal(ServiceState.Stopped); var anotherUtil = Create(serviceName); Expect(anotherUtil.Commandline) .To.Equal(commandline); Expect(anotherUtil.ServiceExe) .To.Equal(serviceExe); Expect(anotherUtil.DisplayName) .To.Equal(displayName); }