private void btnPauseContinue_Click(object sender, EventArgs e) { try { ServiceController serviceController = new ServiceController("ServiceShaka"); if (serviceController.CanPauseAndContinue) { if (serviceController.Status == ServiceControllerStatus.Running) { serviceController.Pause(); lblLog.Text = "服务已暂停"; } else if (serviceController.Status == ServiceControllerStatus.Paused) { serviceController.Continue(); lblLog.Text = "服务已继续"; } else { lblLog.Text = "服务未处于暂停和启动状态"; } } else { lblLog.Text = "服务不能暂停"; } } catch (Exception ex) { } }
private bool PauseService(Service serviceController) { if (!serviceController.CanPauseAndContinue) { Log.LogError(Properties.Resources.ServiceCannotPause, ServiceName, MachineName); return(false); } if (serviceController.Status != ServiceControllerStatus.Running) { Log.LogError(Properties.Resources.ServiceNotStarted, ServiceName, MachineName); return(false); } Log.LogMessage(Properties.Resources.ServicePausing, DisplayName); serviceController.Pause(); // wait until service is paused or timeout expired serviceController.WaitForStatus(ServiceControllerStatus.Paused, TimeSpan.FromMilliseconds(Timeout)); Log.LogMessage(Properties.Resources.ServicePaused, DisplayName); return(true); }
private void MenuPause(object sender, EventArgs e) { System.ServiceProcess.ServiceController tmpSC; tmpSC = new System.ServiceProcess.ServiceController(); tmpSC.MachineName = strMachineName; tmpSC.DisplayName = strDisplayName; try { tmpSC.Pause(); System.Threading.Thread.Sleep(500); //wait for the service to pause while (tmpSC.Status == ServiceControllerStatus.PausePending) { Application.DoEvents(); } lstDrvPaused.Items.Add(lstCurrent.SelectedItem.ToString()); lstCurrent.Items.Remove(lstCurrent.SelectedIndex); lstCurrent.Refresh(); lstDrvPaused.Refresh(); } catch { MessageBox.Show("Service: " + strDisplayName + " Could not be paused !"); } }
private void btnPauseContinue_Click(object sender, EventArgs e) { string serviceName = "EmailService"; try { ServiceController serviceController = new ServiceController(serviceName); if (serviceController.CanPauseAndContinue) { if (serviceController.Status == ServiceControllerStatus.Running) { serviceController.Pause(); lblLog.Text = "服务已暂停"; } else if (serviceController.Status == ServiceControllerStatus.Paused) { serviceController.Continue(); lblLog.Text = "服务已继续"; } else { lblLog.Text = "服务未处于暂停和启动状态"; } } else { lblLog.Text = "服务不能暂停"; } } catch (Exception ex) { _log.Fatal(string.Format("未找到服务:{0} !", serviceName, ex.Message)); } }
internal bool DoPauseService(ServiceController serviceController) { Exception exception = null; bool flag = false; try { serviceController.Pause(); } catch (Win32Exception win32Exception1) { Win32Exception win32Exception = win32Exception1; if (0x426 == win32Exception.NativeErrorCode) { flag = true; } exception = win32Exception; } catch (InvalidOperationException invalidOperationException1) { InvalidOperationException invalidOperationException = invalidOperationException1; Win32Exception innerException = invalidOperationException.InnerException as Win32Exception; if (innerException != null && 0x426 == innerException.NativeErrorCode) { flag = true; } exception = invalidOperationException; } if (exception == null) { if (this.DoWaitForStatus(serviceController, ServiceControllerStatus.Paused, ServiceControllerStatus.PausePending, ServiceResources.SuspendingService, "SuspendServiceFailed", ServiceResources.SuspendServiceFailed)) { return true; } else { return false; } } else { if (!flag) { if (!serviceController.CanPauseAndContinue) { base.WriteNonTerminatingError(serviceController, exception, "CouldNotSuspendServiceNotSupported", ServiceResources.CouldNotSuspendServiceNotSupported, ErrorCategory.CloseError); } } else { base.WriteNonTerminatingError(serviceController, exception, "CouldNotSuspendServiceNotRunning", ServiceResources.CouldNotSuspendServiceNotRunning, ErrorCategory.CloseError); } base.WriteNonTerminatingError(serviceController, exception, "CouldNotSuspendService", ServiceResources.CouldNotSuspendService, ErrorCategory.CloseError); return false; } }
private void ButtonPause_Click(object sender, System.EventArgs e) { //check to see if the service can be paused and continue if (WSController.CanPauseAndContinue == true) { //check the status of the service if (WSController.Status.ToString() == "Running") { WSController.Pause(); } WSController.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Paused); SetButtonStatus(); } }
/// <summary> /// 暂停服务 /// </summary> /// <param name="service"></param> /// <returns></returns> public static bool PauseService(System.ServiceProcess.ServiceController service) { try { if (service == null) { return(false); } if (service.Status != ServiceControllerStatus.Paused && service.Status != ServiceControllerStatus.PausePending) { service.Pause(); service.WaitForStatus(ServiceControllerStatus.Paused); return(true); } } catch { } return(false); }
private void btnPause_Click(object sender, RoutedEventArgs e) { ServiceController serviceController = new ServiceController("ApolloOaService"); if (serviceController.CanPauseAndContinue) { if (serviceController.Status == ServiceControllerStatus.Running) { serviceController.Pause(); lblMessages.Content = "服务已暂停."; } else if (serviceController.Status == ServiceControllerStatus.Paused) { serviceController.Continue(); lblMessages.Content = "服务已恢复."; } } }
public static void PauseService(string serviceName, int timeoutMilliseconds) { ServiceController service = new ServiceController(serviceName); try { if (service.Status == ServiceControllerStatus.Running) { TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds); service.Pause(); service.WaitForStatus(ServiceControllerStatus.Paused, timeout); } } catch { throw; } }
public bool Pause() { ServiceControllerStatus st = sc.Status; switch (st) { case ServiceControllerStatus.Running: case ServiceControllerStatus.StartPending: sc.Pause(); sc.WaitForStatus(ServiceControllerStatus.Paused); st = sc.Status; //再次获取服务状态 return(st == ServiceControllerStatus.Paused); case ServiceControllerStatus.PausePending: case ServiceControllerStatus.Paused: return(true); default: return(false); } }
private void MenuPause(object sender, EventArgs e) { //Pause a service System.ServiceProcess.ServiceController tmpSC = new System.ServiceProcess.ServiceController(); tmpSC.MachineName = strMachineName; tmpSC.DisplayName = strDisplayName; try { //And refresh the listBoxes tmpSC.Pause(); lstSrvPaused.Items.Add(lstCurrent.SelectedItem.ToString()); lstCurrent.Items.Remove(lstCurrent.SelectedItem.ToString()); lstCurrent.Refresh(); lstSrvPaused.Refresh(); } catch { //or may be not possible to stop the service... MessageBox.Show("Service: " + strDisplayName + " Could not be paused !"); } }
private void btnPauseContinue_Click(object sender, RoutedEventArgs e) { ServiceController serviceController = new ServiceController("ServiceHr"); if (serviceController.CanPauseAndContinue) { if (serviceController.Status == ServiceControllerStatus.Running) { serviceController.Pause(); lblStatus.Text = "服务已暂停"; } else if (serviceController.Status == ServiceControllerStatus.Paused) { serviceController.Continue(); lblStatus.Text = "服务已继续"; } else { lblStatus.Text = "服务未处于暂停和启动状态"; } } else lblStatus.Text = "服务不能暂停"; }
public void Pause_Service_Disabled () { if (RunningOnUnix) Assert.Ignore ("Running on Unix."); ServiceController sc1 = new ServiceController ("NetDDE", "."); ServiceController sc2 = new ServiceController ("NetDDE", "."); Assert.AreEqual (ServiceControllerStatus.Stopped, sc1.Status, "#A1"); Assert.AreEqual (ServiceControllerStatus.Stopped, sc2.Status, "#A2"); try { sc1.Pause (); Assert.Fail ("#B1"); } catch (InvalidOperationException ex) { // Cannot pause NetDDE service on computer '.' Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#B2"); Assert.IsNotNull (ex.Message, "#B3"); Assert.IsTrue (ex.Message.IndexOf ("NetDDE") != -1, "#B4"); Assert.IsTrue (ex.Message.IndexOf ("'.'") != -1, "#B5"); Assert.IsNotNull (ex.InnerException, "#B6"); // The service has not been started Assert.AreEqual (typeof (Win32Exception), ex.InnerException.GetType (), "#B7"); Win32Exception win32Error = (Win32Exception) ex.InnerException; //Assert.AreEqual (-2147467259, win32Error.ErrorCode, "#B8"); Assert.IsNotNull (win32Error.Message, "#B9"); Assert.AreEqual (1062, win32Error.NativeErrorCode, "#B10"); Assert.IsNull (win32Error.InnerException, "#B11"); } Assert.AreEqual (ServiceControllerStatus.Stopped, sc1.Status, "#C1"); Assert.AreEqual (ServiceControllerStatus.Stopped, sc2.Status, "#C2"); }
public void Pause_Machine_DoesNotExist () { if (RunningOnUnix) Assert.Ignore ("Running on Unix."); ServiceController sc = new ServiceController ("Schedule", "doesnotexist"); try { sc.Pause (); Assert.Fail ("#1"); } catch (InvalidOperationException ex) { // Cannot open Service Control Manager on computer 'doesnotexist'. // This operation might require other priviliges Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#2"); Assert.IsNotNull (ex.Message, "#3"); Assert.IsTrue (ex.Message.IndexOf ("'doesnotexist'") != -1, "#4"); Assert.IsNotNull (ex.InnerException, "#5"); // The RPC server is unavailable Assert.AreEqual (typeof (Win32Exception), ex.InnerException.GetType (), "#6"); Win32Exception win32Error = (Win32Exception) ex.InnerException; //Assert.AreEqual (-2147467259, win32Error.ErrorCode, "#7"); Assert.IsNotNull (win32Error.Message, "#8"); Assert.AreEqual (1722, win32Error.NativeErrorCode, "#9"); Assert.IsNull (win32Error.InnerException, "#10"); } }
/// <summary> /// This will pause the service. /// </summary> /// <param name="serviceController">service to pause</param> /// <returns>true iff the service was paused</returns> internal bool DoPauseService(ServiceController serviceController) { Exception exception = null; bool serviceNotRunning = false; try { serviceController.Pause(); } catch (Win32Exception e) { if (NativeMethods.ERROR_SERVICE_NOT_ACTIVE == e.NativeErrorCode) { serviceNotRunning = true; } exception = e; } catch (InvalidOperationException e) { Win32Exception eInner = e.InnerException as Win32Exception; if (null != eInner && NativeMethods.ERROR_SERVICE_NOT_ACTIVE == eInner.NativeErrorCode) { serviceNotRunning = true; } exception = e; } if (null != exception) { // This service refused to accept the pause command, // so write a non-terminating error. string resourceIdAndErrorId = ServiceResources.CouldNotSuspendService; if (serviceNotRunning) { WriteNonTerminatingError(serviceController, exception, "CouldNotSuspendServiceNotRunning", ServiceResources.CouldNotSuspendServiceNotRunning, ErrorCategory.CloseError); } else if (!serviceController.CanPauseAndContinue) { WriteNonTerminatingError(serviceController, exception, "CouldNotSuspendServiceNotSupported", ServiceResources.CouldNotSuspendServiceNotSupported, ErrorCategory.CloseError); } WriteNonTerminatingError(serviceController, exception, "CouldNotSuspendService", ServiceResources.CouldNotSuspendService, ErrorCategory.CloseError); return false; } // ServiceController.Pause will return // before the service is actually paused. if (!DoWaitForStatus( serviceController, ServiceControllerStatus.Paused, ServiceControllerStatus.PausePending, ServiceResources.SuspendingService, "SuspendServiceFailed", ServiceResources.SuspendServiceFailed)) { return false; } return true; }
private void btnPause_Click(object sender, EventArgs e) { ServiceController sc = new ServiceController(serviceName); if (sc != null) { sc.Pause(); sc.WaitForStatus(ServiceControllerStatus.Paused); } _parentDlg.commit = true; SetData(); }
static void Main(string[] args) { ServiceController[] scServices; scServices = ServiceController.GetServices(); foreach (ServiceController scTemp in scServices) { if (scTemp.ServiceName == "Simple Service") { // Display properties for the Simple Service sample // from the ServiceBase example. ServiceController sc = new ServiceController("Simple Service"); Console.WriteLine("Status = " + sc.Status); Console.WriteLine("Can Pause and Continue = " + sc.CanPauseAndContinue); Console.WriteLine("Can ShutDown = " + sc.CanShutdown); Console.WriteLine("Can Stop = " + sc.CanStop); if (sc.Status == ServiceControllerStatus.Stopped) { sc.Start(); while (sc.Status == ServiceControllerStatus.Stopped) { Thread.Sleep(1000); sc.Refresh(); } } // Issue custom commands to the service // enum SimpleServiceCustomCommands // { StopWorker = 128, RestartWorker, CheckWorker }; sc.ExecuteCommand((int)SimpleServiceCustomCommands.StopWorker); sc.ExecuteCommand((int)SimpleServiceCustomCommands.RestartWorker); sc.Pause(); while (sc.Status != ServiceControllerStatus.Paused) { Thread.Sleep(1000); sc.Refresh(); } Console.WriteLine("Status = " + sc.Status); sc.Continue(); while (sc.Status == ServiceControllerStatus.Paused) { Thread.Sleep(1000); sc.Refresh(); } Console.WriteLine("Status = " + sc.Status); sc.Stop(); while (sc.Status != ServiceControllerStatus.Stopped) { Thread.Sleep(1000); sc.Refresh(); } Console.WriteLine("Status = " + sc.Status); String[] argArray = new string[] { "ServiceController arg1", "ServiceController arg2" }; sc.Start(argArray); while (sc.Status == ServiceControllerStatus.Stopped) { Thread.Sleep(1000); sc.Refresh(); } Console.WriteLine("Status = " + sc.Status); // Display the event log entries for the custom commands // and the start arguments. EventLog el = new EventLog("Application"); EventLogEntryCollection elec = el.Entries; foreach (EventLogEntry ele in elec) { if (ele.Source.IndexOf("SimpleService.OnCustomCommand") >= 0 | ele.Source.IndexOf("SimpleService.Arguments") >= 0) Console.WriteLine(ele.Message); } } } Console.ReadKey(); }
public void Constructor1 () { if (RunningOnUnix) Assert.Ignore ("Running on Unix."); ServiceController sc = new ServiceController (); try { bool value = sc.CanPauseAndContinue; Assert.Fail ("#A1: " + value.ToString ()); } catch (ArgumentException ex) { // Service name contains invalid characters, is empty or is // too long (max length = 80) Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#A2"); Assert.IsNotNull (ex.Message, "#A3"); Assert.IsTrue (ex.Message.IndexOf (" ") != -1, "#A4"); Assert.IsTrue (ex.Message.IndexOf ("80") != -1, "#A5"); Assert.IsNull (ex.ParamName, "#A6"); Assert.IsNull (ex.InnerException, "#A7"); } try { bool value = sc.CanShutdown; Assert.Fail ("#B1: " + value.ToString ()); } catch (ArgumentException ex) { // Service name contains invalid characters, is empty or is // too long (max length = 80) Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#B2"); Assert.IsNotNull (ex.Message, "#B3"); Assert.IsTrue (ex.Message.IndexOf (" ") != -1, "#B4"); Assert.IsTrue (ex.Message.IndexOf ("80") != -1, "#B5"); Assert.IsNull (ex.ParamName, "#B6"); Assert.IsNull (ex.InnerException, "#B7"); } try { bool value = sc.CanStop; Assert.Fail ("#C1: " + value.ToString ()); } catch (ArgumentException ex) { // Service name contains invalid characters, is empty or is // too long (max length = 80) Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#C2"); Assert.IsNotNull (ex.Message, "#C3"); Assert.IsTrue (ex.Message.IndexOf (" ") != -1, "#C4"); Assert.IsTrue (ex.Message.IndexOf ("80") != -1, "#C5"); Assert.IsNull (ex.ParamName, "#C6"); Assert.IsNull (ex.InnerException, "#C7"); } // closing the ServiceController does not result in exception sc.Close (); try { sc.Continue (); Assert.Fail ("#D1"); } catch (ArgumentException ex) { // Service name contains invalid characters, is empty or is // too long (max length = 80) Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#D2"); Assert.IsNotNull (ex.Message, "#D3"); Assert.IsTrue (ex.Message.IndexOf (" ") != -1, "#D4"); Assert.IsTrue (ex.Message.IndexOf ("80") != -1, "#D5"); Assert.IsNull (ex.ParamName, "#D6"); Assert.IsNull (ex.InnerException, "#D7"); } try { Assert.Fail ("#E1: " + sc.DependentServices.Length); } catch (ArgumentException ex) { // Service name contains invalid characters, is empty or is // too long (max length = 80) Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#E2"); Assert.IsNotNull (ex.Message, "#E3"); Assert.IsTrue (ex.Message.IndexOf (" ") != -1, "#E4"); Assert.IsTrue (ex.Message.IndexOf ("80") != -1, "#E5"); Assert.IsNull (ex.ParamName, "#E6"); Assert.IsNull (ex.InnerException, "#E7"); } Assert.IsNotNull (sc.DisplayName, "#F1"); Assert.AreEqual (string.Empty, sc.DisplayName, "#F2"); try { sc.ExecuteCommand (0); Assert.Fail ("#G1"); } catch (ArgumentException ex) { // Service name contains invalid characters, is empty or is // too long (max length = 80) Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#G2"); Assert.IsNotNull (ex.Message, "#G3"); Assert.IsTrue (ex.Message.IndexOf (" ") != -1, "#G4"); Assert.IsTrue (ex.Message.IndexOf ("80") != -1, "#G5"); Assert.IsNull (ex.ParamName, "#G6"); Assert.IsNull (ex.InnerException, "#G7"); } Assert.IsNotNull (sc.MachineName, "#H1"); Assert.AreEqual (".", sc.MachineName, "#H2"); try { sc.Pause (); Assert.Fail ("#I1"); } catch (ArgumentException ex) { // Service name contains invalid characters, is empty or is // too long (max length = 80) Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#I2"); Assert.IsNotNull (ex.Message, "#I3"); Assert.IsTrue (ex.Message.IndexOf (" ") != -1, "#I4"); Assert.IsTrue (ex.Message.IndexOf ("80") != -1, "#I5"); Assert.IsNull (ex.ParamName, "#I6"); Assert.IsNull (ex.InnerException, "#I7"); } }
public void Pause_Service_Stopped () { if (RunningOnUnix) Assert.Ignore ("Running on Unix."); ServiceController sc1 = new ServiceController ("Schedule", "."); ServiceController sc2 = new ServiceController ("Schedule", "."); Assert.AreEqual (ServiceControllerStatus.Running, sc1.Status, "#A1"); Assert.AreEqual (ServiceControllerStatus.Running, sc2.Status, "#A2"); sc1.Stop (); try { Assert.AreEqual (ServiceControllerStatus.Running, sc1.Status, "#B1"); Assert.AreEqual (ServiceControllerStatus.Running, sc2.Status, "#B2"); sc1.WaitForStatus (ServiceControllerStatus.Stopped, new TimeSpan (0, 0, 5)); Assert.AreEqual (ServiceControllerStatus.Stopped, sc1.Status, "#C1"); Assert.AreEqual (ServiceControllerStatus.Running, sc2.Status, "#C2"); sc1.Pause (); Assert.Fail ("#D1"); } catch (InvalidOperationException ex) { // Cannot pause Schedule service on computer '.' Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#D2"); Assert.IsNotNull (ex.Message, "#D3"); Assert.IsTrue (ex.Message.IndexOf ("Schedule") != -1, "#D4"); Assert.IsTrue (ex.Message.IndexOf ("'.'") != -1, "#D5"); Assert.IsNotNull (ex.InnerException, "#D6"); // The service has not been started Assert.AreEqual (typeof (Win32Exception), ex.InnerException.GetType (), "#D7"); Win32Exception win32Error = (Win32Exception) ex.InnerException; //Assert.AreEqual (-2147467259, win32Error.ErrorCode, "#D8"); Assert.IsNotNull (win32Error.Message, "#D9"); Assert.AreEqual (1062, win32Error.NativeErrorCode, "#D10"); Assert.IsNull (win32Error.InnerException, "#D11"); } finally { EnsureServiceIsRunning (sc1); sc2.Refresh (); } Assert.AreEqual (ServiceControllerStatus.Running, sc1.Status, "#E1"); Assert.AreEqual (ServiceControllerStatus.Running, sc2.Status, "#E2"); }
public void ExecuteCommand_Service_ContinuePending () { if (RunningOnUnix) Assert.Ignore ("Running on Unix."); ServiceController sc = new ServiceController (CONTROLLABLE_SERVICE.ServiceName, "."); Assert.AreEqual (ServiceControllerStatus.Running, sc.Status, "#A"); sc.Pause (); try { sc.WaitForStatus (ServiceControllerStatus.Paused, new TimeSpan (0, 0, 5)); Assert.AreEqual (ServiceControllerStatus.Paused, sc.Status, "#B"); sc.Continue (); sc.ExecuteCommand (128); try { sc.ExecuteCommand (127); Assert.Fail ("#C1"); } catch (InvalidOperationException ex) { // Cannot control XXX service on computer '.' Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#C2"); Assert.IsNotNull (ex.Message, "#C3"); Assert.IsTrue (ex.Message.IndexOf (CONTROLLABLE_SERVICE.ServiceName) != -1, "#C4"); Assert.IsTrue (ex.Message.IndexOf ("'.'") != -1, "#C5"); Assert.IsNotNull (ex.InnerException, "#C6"); // The parameter is incorrect Assert.AreEqual (typeof (Win32Exception), ex.InnerException.GetType (), "#C7"); Win32Exception win32Error = (Win32Exception) ex.InnerException; //Assert.AreEqual (-2147467259, win32Error.ErrorCode, "#C8"); Assert.IsNotNull (win32Error.Message, "#C9"); Assert.AreEqual (87, win32Error.NativeErrorCode, "#C10"); Assert.IsNull (win32Error.InnerException, "#C11"); } } finally { EnsureServiceIsRunning (sc); } Assert.AreEqual (ServiceControllerStatus.Running, sc.Status, "#E"); }
/// <summary> /// Pause the service with the given name and wait until the service status is paused. /// If the service status is not paused after the given timeout then the service is considered not paused. /// </summary> /// <param name="serviceName">The name of the service</param> /// <param name="timeout">The timeout.</param> /// <returns>True if the service has been paused. Otherwise, false.</returns> public static bool PauseService(string serviceName, TimeSpan timeout) { try { bool timeoutEnabled = (timeout.CompareTo(TimeSpan.Zero) > 0); using (ServiceController c = new ServiceController(serviceName)) { c.Refresh(); if (timeoutEnabled && c.Status == ServiceControllerStatus.Paused) return true; if (!timeoutEnabled && (c.Status == ServiceControllerStatus.Paused || c.Status == ServiceControllerStatus.PausePending)) return true; c.Pause(); if (timeoutEnabled) c.WaitForStatus(ServiceControllerStatus.Paused, timeout); return true; } } catch (Exception e) { Utils.Trace(e, "Unexpected error pausing service {0}.", serviceName); return false; } }
/// <summary> /// The main entry point for the application. /// </summary> /// <returns>S_OK (0) if no error has occurred, otherwise the error number.</returns> static int Main(string[] args) { var nResult = S_OK; // Setup your default properties ConfigurationFilePath = VirtualServiceStore.VIRTUAL_SERVICE_CONFIG_FOLDER; try { // Declare variables ServiceController scController = null; CustomServiceInstaller cusInstaller = new CustomServiceInstaller(); var bSuccess = false; // Look in the application settings of the configuration file. if (String.IsNullOrEmpty(ConfigurationManager.AppSettings["ServiceName"]) == false) ServiceName = ConfigurationManager.AppSettings["ServiceName"]; else ServiceName = WindowsServiceConstants.SERVICE_NAME; // Parse out the command line parameters ParseCommandLineArguments(args); // Parse out the registry items. ParseRegistry(); // Create your service controller scController = new ServiceController(ServiceName); // Determine how many command line arguments accompanied the executable if (args.Length > 0) { switch (args[0].ToUpper()) { case "-INSTALL": { // Install the service Install(cusInstaller); // Write a success message out Console.WriteLine("The service was installed successfully."); break; } case "-UNINSTALL": case "-REMOVE": { // Make sure that the service is not already uninstalled (never installed) if (cusInstaller.DoesServiceExists(ServiceName) == true) { // Attempt to uninstall the service. bSuccess = cusInstaller.UnInstallService(ServiceName, WindowsServiceConstants.TIMEOUT, WindowsServiceConstants.POLLDELAY); if (bSuccess == false) throw new Exception("Unable to uninstall the service successfully."); // Write out a success message Console.WriteLine("The service was uninstalled successfully."); } else throw new Exception("The service does not exist as an installed service."); break; } case "-STATUS": { // Write the status of the service to the console Console.WriteLine("Service Status:" + scController.Status.ToString() + Environment.NewLine); break; } case "-START": { // Make sure that the service is stopped if (scController.Status == ServiceControllerStatus.Stopped) { // Attempt to start the service scController.Start(); Console.WriteLine("The service was started successfully."); } else Console.WriteLine("Current Service State:" + scController.Status.ToString() + Environment.NewLine + "The service is not in a state which can be started."); break; } case "-STOP": { // Make sure that the service is stopped if (scController.Status == ServiceControllerStatus.Running) { // Attempt to start the service scController.Stop(); Console.WriteLine("The service was stopped successfully."); } else Console.WriteLine("Current Service State:" + scController.Status.ToString() + Environment.NewLine + "The service is not in a state which can be stopped."); break; } case "-PAUSE": { // Make sure that the service is stopped if (scController.Status == ServiceControllerStatus.Running) { // Attempt to start the service scController.Pause(); Console.WriteLine("The service was paused successfully."); } else Console.WriteLine("Current Service State:" + scController.Status.ToString() + Environment.NewLine + "The service is not in a state which can be paused."); break; } case "-CONTINUE": case "-RESUME": { // Make sure that the service is stopped if (scController.Status == ServiceControllerStatus.Paused) { // Attempt to start the service scController.Continue(); Console.WriteLine("The service was resumed successfully."); } else Console.WriteLine("Current Service State:" + scController.Status.ToString() + Environment.NewLine + "The service is not in a state which can be resumed."); break; } case "-CONSOLEHOST": { // Create the console host service controller var svcConsoleHostCtrl = new ServicesManagerConsoleHostContoller(); if (String.IsNullOrEmpty(ConfigurationFilePath) == false) svcConsoleHostCtrl.ConfigurationFolder = ConfigurationFilePath; svcConsoleHostCtrl.Start(); break; } default: { // Output the message telling them about the valid arguments Console.WriteLine(CMDLINE_ARG_MSG); throw new InvalidOperationException("Command line arguments not recognized."); } } } else { // Since no arguments were passed, just attempt to start the service as a normal // windows service (The windows service control manager calls this methods) ServiceBase[] ServicesToRun; ServicesToRun = new ServiceBase[] { new VSFWinServ(ConfigurationFilePath) }; ServiceBase.Run(ServicesToRun); } } catch (Exception ex) { if (Debugger.IsAttached) Debugger.Break(); Trace.WriteLine(ex); Console.WriteLine("\nUnable to perform the selected action\n\nSource: " + ex.Source + "\nDescription: " + ex.Message); nResult = 69; } return nResult; }
/// <summary> /// Pauses this instance. /// </summary> public void Pause() { using (var serviceController = new ServiceController(ESyncServiceName)) { serviceController.Pause(); if (!WaitForStatus(serviceController, ServiceControllerStatus.Paused, ServiceControllerStatus.PausePending)) { throw new InvalidOperationException(string.Format("Could not pause the service {0}. See event log for details.", ESyncServiceName)); } } }
public void CanPauseAndContinue_Service_Paused () { if (RunningOnUnix) Assert.Ignore ("Running on Unix."); ServiceController sc1 = new ServiceController (CONTROLLABLE_SERVICE.ServiceName, "."); ServiceController sc2 = new ServiceController (CONTROLLABLE_SERVICE.ServiceName, "."); Assert.AreEqual (ServiceControllerStatus.Running, sc1.Status, "#A1"); Assert.AreEqual (ServiceControllerStatus.Running, sc2.Status, "#A2"); Assert.IsTrue (sc1.CanPauseAndContinue, "#B1"); Assert.IsTrue (sc2.CanPauseAndContinue, "#B2"); sc1.Pause (); try { Assert.IsTrue (sc1.CanPauseAndContinue, "#C1"); Assert.IsTrue (sc2.CanPauseAndContinue, "#C2"); sc1.WaitForStatus (ServiceControllerStatus.Paused, new TimeSpan (0, 0, 5)); Assert.IsTrue (sc1.CanPauseAndContinue, "#D1"); Assert.IsTrue (sc2.CanPauseAndContinue, "#D2"); } finally { EnsureServiceIsRunning (sc1); sc2.Refresh (); } Assert.IsTrue (sc1.CanPauseAndContinue, "#E1"); Assert.IsTrue (sc2.CanPauseAndContinue, "#E2"); Assert.AreEqual (ServiceControllerStatus.Running, sc1.Status, "#F1"); Assert.AreEqual (ServiceControllerStatus.Running, sc2.Status, "#F2"); }
public void Pause_Service_DoesNotExist () { if (RunningOnUnix) Assert.Ignore ("Running on Unix."); ServiceController sc = new ServiceController ("doesnotexist", "."); try { sc.Pause (); Assert.Fail ("#1"); } catch (InvalidOperationException ex) { // Cannot open doesnotexist service on computer '.' Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#2"); Assert.IsNotNull (ex.Message, "#3"); Assert.IsTrue (ex.Message.IndexOf ("doesnotexist") != -1, "#4"); Assert.IsTrue (ex.Message.IndexOf ("'.'") != -1, "#5"); Assert.IsNotNull (ex.InnerException, "#6"); // The filename, directory name, or volume label is incorrect Assert.AreEqual (typeof (Win32Exception), ex.InnerException.GetType (), "#7"); Win32Exception win32Error = (Win32Exception) ex.InnerException; //Assert.AreEqual (-2147467259, win32Error.ErrorCode, "#8"); Assert.IsNotNull (win32Error.Message, "#9"); Assert.AreEqual (1060, win32Error.NativeErrorCode, "#10"); Assert.IsNull (win32Error.InnerException, "#11"); } }
public static void Pause(ServiceController ser) { if (ser != null && ser.Status == ServiceControllerStatus.Running) ser.Pause();//ser.Pause();暂停 }
public void Pause_Service_OperationNotValid () { if (RunningOnUnix) Assert.Ignore ("Running on Unix."); ServiceController sc1 = new ServiceController ("SamSs", "."); ServiceController sc2 = new ServiceController ("SamSs", "."); Assert.AreEqual (ServiceControllerStatus.Running, sc1.Status, "#A1"); Assert.AreEqual (ServiceControllerStatus.Running, sc2.Status, "#A2"); try { sc1.Pause (); Assert.Fail ("#B1"); } catch (InvalidOperationException ex) { // Cannot pause SamSs service on computer '.' Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#B2"); Assert.IsNotNull (ex.Message, "#B3"); Assert.IsTrue (ex.Message.IndexOf ("SamSs") != -1, "#B4"); Assert.IsTrue (ex.Message.IndexOf ("'.'") != -1, "#B5"); Assert.IsNotNull (ex.InnerException, "#B6"); // The requested control is not valid for this service Assert.AreEqual (typeof (Win32Exception), ex.InnerException.GetType (), "#B7"); Win32Exception win32Error = (Win32Exception) ex.InnerException; //Assert.AreEqual (-2147467259, win32Error.ErrorCode, "#B8"); Assert.IsNotNull (win32Error.Message, "#B9"); Assert.AreEqual (1052, win32Error.NativeErrorCode, "#B10"); Assert.IsNull (win32Error.InnerException, "#B11"); } Assert.AreEqual (ServiceControllerStatus.Running, sc1.Status, "#C1"); Assert.AreEqual (ServiceControllerStatus.Running, sc2.Status, "#C2"); }
/// Execute action public override object Execute() { string svcName = Context.TransformStr(ServiceName, Transform); string machineName = Context.TransformStr(MachineName, Transform); if (Command==ServiceCommand.IsInstalled) { bool installed = false; foreach (ServiceController svc in ServiceController.GetServices(machineName)) { if (string.Compare(svc.ServiceName, svcName, StringComparison.OrdinalIgnoreCase) == 0) { installed = true; break; } } Context.OutTo(Context.TransformStr(OutTo, Transform), installed); return null; } using (var sc = new ServiceController(svcName,machineName)) { switch (Command) { case ServiceCommand.Stop: case ServiceCommand.StopWait: if (sc.Status == ServiceControllerStatus.Stopped) break; if (sc.Status != ServiceControllerStatus.Stopped && sc.Status != ServiceControllerStatus.StopPending) sc.Stop(); if (Command == ServiceCommand.StopWait) goto case ServiceCommand.WaitForStopped; break; case ServiceCommand.Start: case ServiceCommand.StartWait: if (sc.Status == ServiceControllerStatus.Running) break; if (sc.Status != ServiceControllerStatus.Running && sc.Status != ServiceControllerStatus.StartPending) sc.Start(); if (Command == ServiceCommand.StartWait || Command == ServiceCommand.RestartWait) goto case ServiceCommand.WaitForRunning; break; case ServiceCommand.Restart: case ServiceCommand.RestartWait: if (sc.Status != ServiceControllerStatus.Stopped) sc.Stop(); sc.WaitForStatus(ServiceControllerStatus.Stopped, Utils.ToTimeSpan(Timeout).Value); goto case ServiceCommand.StartWait; case ServiceCommand.Continue: if (sc.Status!=ServiceControllerStatus.Running && sc.Status!=ServiceControllerStatus.ContinuePending) sc.Continue(); break; case ServiceCommand.Pause: case ServiceCommand.PauseWait: if (sc.Status != ServiceControllerStatus.Paused && sc.Status!=ServiceControllerStatus.PausePending) sc.Pause(); if (Command == ServiceCommand.PauseWait) goto case ServiceCommand.WaitForPaused; break; case ServiceCommand.WaitForRunning: var tm=Utils.ToTimeSpan(Timeout).Value; var swStart=Stopwatch.StartNew(); bool found=false; do { Context.CheckAbort(); try { if (tm<TimeSpan.FromSeconds(2)) sc.WaitForStatus(ServiceControllerStatus.Running, tm); else sc.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(2)); found = true; break; } catch (System.ServiceProcess.TimeoutException e) { if (sc.Status == ServiceControllerStatus.Stopped) break; } } while (swStart.Elapsed < tm); if (!found) throw new InvalidOperationException("Service has failed to start"); break; case ServiceCommand.WaitForPaused: sc.WaitForStatus(ServiceControllerStatus.Paused, Utils.ToTimeSpan(Timeout).Value); break; case ServiceCommand.WaitForStopped: sc.WaitForStatus(ServiceControllerStatus.Stopped, Utils.ToTimeSpan(Timeout).Value); break; case ServiceCommand.Status: Context.OutTo(Context.TransformStr(OutTo, Transform), sc.Status); break; default: throw new ParsingException("Unknown action: " + Command); } } return null; }
public void Pause_ServiceName_Empty () { ServiceController sc = new ServiceController (); try { sc.Pause (); Assert.Fail ("#1"); } catch (ArgumentException ex) { // Service name contains invalid characters, is empty or is // too long (max length = 80) Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2"); Assert.IsNotNull (ex.Message, "#3"); Assert.IsTrue (ex.Message.IndexOf (" ") != -1, "#4"); Assert.IsTrue (ex.Message.IndexOf ("80") != -1, "#5"); Assert.IsNull (ex.ParamName, "#6"); Assert.IsNull (ex.InnerException, "#7"); } }
/// <summary> /// Pauses the service identified by <see cref="ServiceName" /> and /// <see cref="MachineName" />. /// </summary> /// <param name="serviceController"><see cref="ServiceController" /> instance for controlling the service identified by <see cref="ServiceName" /> and <see cref="MachineName" />.</param> private void PauseService(ServiceController serviceController) { try { if (serviceController.Status == ServiceControllerStatus.Running) { if (serviceController.CanPauseAndContinue) { if (serviceController.Status != ServiceControllerStatus.Running) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA3010"), ServiceName, MachineName), Location); } else { serviceController.Pause(); } } else { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA3011"), ServiceName, MachineName), Location); } } else { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA3010"), ServiceName, MachineName), Location); } // wait until service is paused or timeout expired serviceController.WaitForStatus(ServiceControllerStatus.Paused, TimeSpan.FromMilliseconds(Timeout)); } catch (BuildException ex) { // rethrow exception throw ex; } catch (Exception ex) { throw new BuildException(string.Format(CultureInfo.InvariantCulture, ResourceUtils.GetString("NA3009"), ServiceName, MachineName), Location, ex); } }
public void CanStop_Service_Paused () { if (RunningOnUnix) Assert.Ignore ("Running on Unix."); ServiceController sc1 = new ServiceController ("Schedule", "."); ServiceController sc2 = new ServiceController ("Schedule", "."); Assert.AreEqual (ServiceControllerStatus.Running, sc1.Status, "#A1"); Assert.AreEqual (ServiceControllerStatus.Running, sc2.Status, "#A2"); Assert.IsTrue (sc1.CanStop, "#B1"); Assert.IsTrue (sc2.CanStop, "#B2"); sc1.Pause (); try { Assert.IsTrue (sc1.CanStop, "#C1"); Assert.IsTrue (sc2.CanStop, "#C2"); sc1.WaitForStatus (ServiceControllerStatus.Paused, new TimeSpan (0, 0, 5)); Assert.IsTrue (sc1.CanStop, "#D1"); Assert.IsTrue (sc2.CanStop, "#D2"); } finally { EnsureServiceIsRunning (sc1); sc2.Refresh (); } Assert.IsTrue (sc1.CanStop, "#E1"); Assert.IsTrue (sc2.CanStop, "#E2"); Assert.AreEqual (ServiceControllerStatus.Running, sc1.Status, "#F1"); Assert.AreEqual (ServiceControllerStatus.Running, sc2.Status, "#F2"); }
public void ExecuteCommand_Service_Paused () { if (RunningOnUnix) Assert.Ignore ("Running on Unix."); ServiceController sc = new ServiceController ("Schedule", "."); Assert.AreEqual (ServiceControllerStatus.Running, sc.Status, "#A"); sc.Pause (); try { sc.WaitForStatus (ServiceControllerStatus.Paused, new TimeSpan (0, 0, 5)); Assert.AreEqual (ServiceControllerStatus.Paused, sc.Status, "#B"); sc.ExecuteCommand (154); sc.Refresh (); Assert.AreEqual (ServiceControllerStatus.Paused, sc.Status, "#C"); //sc.ExecuteCommand (127); } finally { EnsureServiceIsRunning (sc); } Assert.AreEqual (ServiceControllerStatus.Running, sc.Status, "#D"); }
public void PauseAndContinue() { var controller = new ServiceController(_testService.TestServiceName); Assert.Equal(ServiceControllerStatus.Running, controller.Status); for (int i = 0; i < 2; i++) { controller.Pause(); controller.WaitForStatus(ServiceControllerStatus.Paused, _testService.ControlTimeout); Assert.Equal(ServiceControllerStatus.Paused, controller.Status); controller.Continue(); controller.WaitForStatus(ServiceControllerStatus.Running, _testService.ControlTimeout); Assert.Equal(ServiceControllerStatus.Running, controller.Status); } }
public void ExecuteCommand_Service_PausePending () { if (RunningOnUnix) Assert.Ignore ("Running on Unix."); ServiceController sc = new ServiceController ("Schedule", "."); Assert.AreEqual (ServiceControllerStatus.Running, sc.Status, "#A"); sc.Pause (); try { sc.ExecuteCommand (128); try { sc.ExecuteCommand (127); Assert.Fail ("#B1"); } catch (InvalidOperationException ex) { // Cannot control Schedule service on computer '.' Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#B2"); Assert.IsNotNull (ex.Message, "#B3"); Assert.IsTrue (ex.Message.IndexOf ("Schedule") != -1, "#B4"); Assert.IsTrue (ex.Message.IndexOf ("'.'") != -1, "#B5"); Assert.IsNotNull (ex.InnerException, "#B6"); // The parameter is incorrect Assert.AreEqual (typeof (Win32Exception), ex.InnerException.GetType (), "#B7"); Win32Exception win32Error = (Win32Exception) ex.InnerException; //Assert.AreEqual (-2147467259, win32Error.ErrorCode, "#B8"); Assert.IsNotNull (win32Error.Message, "#B9"); Assert.AreEqual (87, win32Error.NativeErrorCode, "#B10"); Assert.IsNull (win32Error.InnerException, "#B11"); } } finally { EnsureServiceIsRunning (sc); } Assert.AreEqual (ServiceControllerStatus.Running, sc.Status, "#C"); }
private bool PauseService(Service serviceController) { if (!serviceController.CanPauseAndContinue) { Log.LogError(Properties.Resources.ServiceCannotPause, ServiceName, MachineName); return false; } if (serviceController.Status != ServiceControllerStatus.Running) { Log.LogError(Properties.Resources.ServiceNotStarted, ServiceName, MachineName); return false; } Log.LogMessage(Properties.Resources.ServicePausing, DisplayName); serviceController.Pause(); // wait until service is paused or timeout expired serviceController.WaitForStatus(ServiceControllerStatus.Paused, TimeSpan.FromMilliseconds(Timeout)); Log.LogMessage(Properties.Resources.ServicePaused, DisplayName); return true; }
public static async Task<bool> PauseService( [NotNull] string serviceName, CancellationToken token = default(CancellationToken)) { if (serviceName == null) throw new ArgumentNullException("serviceName"); try { new ServiceControllerPermission( ServiceControllerPermissionAccess.Control, Environment.MachineName, serviceName).Assert(); using (ServiceController controller = new ServiceController(serviceName, Environment.MachineName)) switch (controller.Status) { case ServiceControllerStatus.Running: controller.Pause(); return await WaitForAsync(controller, ServiceControllerStatus.Paused, token) .ConfigureAwait(false); case ServiceControllerStatus.ContinuePending: case ServiceControllerStatus.StartPending: if (!await WaitForAsync(controller, ServiceControllerStatus.Running, token) .ConfigureAwait(false)) return false; controller.Pause(); return await WaitForAsync(controller, ServiceControllerStatus.Paused, token) .ConfigureAwait(false); case ServiceControllerStatus.Paused: return true; case ServiceControllerStatus.PausePending: return await WaitForAsync(controller, ServiceControllerStatus.Paused, token) .ConfigureAwait(false); default: return false; } } catch (TaskCanceledException) { return false; } }