/// <summary> /// Start the service with the given name and wait until the status of the service is running. /// If the service status is not running after the given timeout then the service is considered not started. /// You can call this method after stop or pause the service in order to re-start it. /// </summary> /// <param name="serviceName">The name of the service</param> /// <param name="timeout">The timeout.</param> /// <returns>True if the service has been started. Otherwise, false.</returns> public static bool StartService(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.Running) return true; if (!timeoutEnabled && (c.Status == ServiceControllerStatus.Running || c.Status == ServiceControllerStatus.StartPending || c.Status == ServiceControllerStatus.ContinuePending)) return true; if (c.Status == ServiceControllerStatus.Paused || c.Status == ServiceControllerStatus.ContinuePending) c.Continue(); else if (c.Status == ServiceControllerStatus.Stopped || c.Status == ServiceControllerStatus.StartPending) c.Start(); if (timeoutEnabled) c.WaitForStatus(ServiceControllerStatus.Running, timeout); return true; } } catch (Exception e) { Utils.Trace(e, "Unexpected error starting service {0}.", serviceName); return false; } }
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 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)); } }
private bool ContinueService(Service serviceController) { if (serviceController.Status == ServiceControllerStatus.Running) { return(true); // already running } if (!serviceController.CanPauseAndContinue) { Log.LogError(Properties.Resources.ServiceCannotContinue, ServiceName, MachineName); return(false); } if (serviceController.Status != ServiceControllerStatus.Paused) { Log.LogError(Properties.Resources.ServiceNotPaused, ServiceName, MachineName); return(false); } Log.LogMessage(Properties.Resources.ServiceContinuing, DisplayName); serviceController.Continue(); // wait until service is running or timeout expired serviceController.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromMilliseconds(Timeout)); Log.LogMessage(Properties.Resources.ServiceContinued, DisplayName); return(true); }
private void MenuStart(object sender, EventArgs e) { System.ServiceProcess.ServiceController tmpSC = new System.ServiceProcess.ServiceController(); tmpSC.MachineName = strMachineName; tmpSC.DisplayName = strDisplayName; try { //When a service is paused, it has to continue. //Start in this case is not possible. if (lstCurrent.Equals(lstSrvPaused)) { tmpSC.Continue(); } else { tmpSC.Start(); } System.Threading.Thread.Sleep(500); //Loop while the service is pending the continue state while (tmpSC.Status == ServiceControllerStatus.ContinuePending) { Application.DoEvents(); } //after starting the service, refresh the listBoxes if (tmpSC.Status == ServiceControllerStatus.Running) { lstSrvRun.Items.Add(lstCurrent.SelectedItem.ToString()); lstCurrent.Items.Remove(lstCurrent.SelectedItem.ToString()); //(lstCurrent.SelectedIndex); lstCurrent.Refresh(); lstSrvRun.Refresh(); } //Perhaps it could not start... else { MessageBox.Show(tmpSC.ServiceName + " Cannot be started"); } } catch //Do you have enough permissions to start this service ? { MessageBox.Show("Service: " + strDisplayName + " Could not be started ! "); } }
/// <summary> /// 继续服务 /// </summary> /// <param name="service"></param> /// <returns></returns> public bool ResumeService(System.ServiceProcess.ServiceController service) { try { if (service == null) { return(false); } if (service.Status == ServiceControllerStatus.Paused) { service.Continue(); service.WaitForStatus(ServiceControllerStatus.Running); 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 ContinueService(string serviceName, int timeoutMilliseconds) { ServiceController service = new ServiceController(serviceName); try { if (service.Status == ServiceControllerStatus.Paused) { TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds); service.Continue(); service.WaitForStatus(ServiceControllerStatus.Running, timeout); } } catch { throw; } }
private void ButtonStart_Click(object sender, System.EventArgs e) { //check the status of the service if (WSController.Status.ToString() == "Paused") { WSController.Continue(); } else if (WSController.Status.ToString() == "Stopped") { //get an array of services this service depends upon, loop through //the array and prompt the user to start all required services. ServiceController[] ParentServices = WSController.ServicesDependedOn; //if the length of the array is greater than or equal to 1. if (ParentServices.Length >= 1) { foreach (ServiceController ParentService in ParentServices) { //make sure the parent service is running or at least paused. if (ParentService.Status.ToString() != "Running" || ParentService.Status.ToString() != "Paused") { if (MessageBox.Show("This service is required. Would you like to also start this service?\n" + ParentService.DisplayName, "Required Service", MessageBoxButtons.YesNo).ToString() == "Yes") { //if the user chooses to start the service ParentService.Start(); ParentService.WaitForStatus(ServiceControllerStatus.Running); } else { //otherwise just return. return; } } } } WSController.Start(); } WSController.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Running); SetButtonStatus(); }
//The event assigned to Start driver MenuItem private void MenuStart(object sender, EventArgs e) { System.ServiceProcess.ServiceController tmpSC; tmpSC = new System.ServiceProcess.ServiceController(); tmpSC.MachineName = strMachineName; tmpSC.DisplayName = strDisplayName; try { if (lstCurrent.Equals(lstDrvPaused)) { tmpSC.Continue(); } else { tmpSC.Start(); } //wait for the process to restart System.Threading.Thread.Sleep(500); while (tmpSC.Status == ServiceControllerStatus.ContinuePending) { Application.DoEvents(); } if (tmpSC.Status == ServiceControllerStatus.Running) { lstDrvRun.Items.Add(lstCurrent.SelectedItem.ToString()); lstCurrent.Items.Remove(lstCurrent.SelectedItem.ToString()); lstCurrent.Refresh(); lstDrvRun.Refresh(); } else { MessageBox.Show(tmpSC.ServiceName + " Cannot be started"); } } catch { MessageBox.Show("Service: " + strDisplayName + " Could not be started ! "); } }
public bool Resume() { ServiceControllerStatus st = sc.Status; switch (st) { case ServiceControllerStatus.Paused: case ServiceControllerStatus.PausePending: sc.Continue(); sc.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, 30)); st = sc.Status; //再次获取服务状态 return(st == ServiceControllerStatus.Running); case ServiceControllerStatus.Running: case ServiceControllerStatus.StartPending: return(true); default: return(false); } }
private bool StartService(Service serviceController) { Log.LogMessage(Properties.Resources.ServiceStarting, DisplayName); if (serviceController.Status == ServiceControllerStatus.Paused) { serviceController.Continue(); } else { serviceController.Start(); } // wait until service is running or timeout expired serviceController.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromMilliseconds(Timeout)); Log.LogMessage(Properties.Resources.ServiceStarted, DisplayName); return(true); }
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 Continue_ServiceName_Empty () { ServiceController sc = new ServiceController (); try { sc.Continue (); 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"); } }
public void Continue_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.Continue (); Assert.Fail ("#D1"); } catch (InvalidOperationException ex) { // Cannot resume 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 Continue_Service_Running () { 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.Continue (); Assert.AreEqual (ServiceControllerStatus.Running, sc1.Status, "#B1"); Assert.AreEqual (ServiceControllerStatus.Running, sc2.Status, "#B2"); }
public void Continue_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.Continue (); Assert.Fail ("#B1"); } catch (InvalidOperationException ex) { // Cannot resume 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"); }
public void Continue_Service_DoesNotExist () { if (RunningOnUnix) Assert.Ignore ("Running on Unix."); ServiceController sc = new ServiceController ("doesnotexist", "."); try { sc.Continue (); 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"); } }
/// <summary> /// Resumes this instance. /// </summary> public void Resume() { using (var serviceController = new ServiceController(ESyncServiceName)) { serviceController.Continue(); if (!WaitForStatus(serviceController, ServiceControllerStatus.Running, ServiceControllerStatus.ContinuePending)) { throw new InvalidOperationException(string.Format("Could not resume the service {0}. See event log for details.", ESyncServiceName)); } } }
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"); } }
private void btnResume_Click(object sender, EventArgs e) { ServiceController sc = new ServiceController(serviceName); if (sc != null) { sc.Continue(); sc.WaitForStatus(ServiceControllerStatus.Running); } _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(); }
/// <summary> /// This will resume the service. /// </summary> /// <param name="serviceController">service to resume</param> /// <returns>true iff the service was resumed</returns> internal bool DoResumeService(ServiceController serviceController) { Exception exception = null; bool serviceNotRunning = false; try { serviceController.Continue(); } 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 continue command, // so write a non-terminating error. if (serviceNotRunning) { WriteNonTerminatingError(serviceController, exception, "CouldNotResumeServiceNotRunning", ServiceResources.CouldNotResumeServiceNotRunning, ErrorCategory.CloseError); } else if (!serviceController.CanPauseAndContinue) { WriteNonTerminatingError(serviceController, exception, "CouldNotResumeServiceNotSupported", ServiceResources.CouldNotResumeServiceNotSupported, ErrorCategory.CloseError); } WriteNonTerminatingError(serviceController, exception, "CouldNotResumeService", ServiceResources.CouldNotResumeService, ErrorCategory.CloseError); return false; } // ServiceController.Continue will return // before the service is actually continued. if (!DoWaitForStatus( serviceController, ServiceControllerStatus.Running, ServiceControllerStatus.ContinuePending, ServiceResources.ResumingService, "ResumeServiceFailed", ServiceResources.ResumeServiceFailed)) { return false; } return true; }
private static bool StartService(string serviceName, int timeoutMilliseconds) { var service = new ServiceController(serviceName); try { var timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds); //If paused then Continue the service, do not attempt to start. if (service.Status.Equals(ServiceControllerStatus.Paused)) { service.Continue(); service.WaitForStatus(ServiceControllerStatus.Running, timeout); if (service.Status.Equals(ServiceControllerStatus.Running)) return true; return false; } //Service is not Paused, Start it. service.Start(); service.WaitForStatus(ServiceControllerStatus.Running, timeout); if (service.Status.Equals(ServiceControllerStatus.Running)) return true; return false; } catch (Exception e) { Console.WriteLine("Exception: {0}", e.Message); return false; } }
internal bool DoResumeService(ServiceController serviceController) { Exception exception = null; bool flag = false; try { serviceController.Continue(); } 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.Running, ServiceControllerStatus.ContinuePending, ServiceResources.ResumingService, "ResumeServiceFailed", ServiceResources.ResumeServiceFailed)) { return true; } else { return false; } } else { if (!flag) { if (!serviceController.CanPauseAndContinue) { base.WriteNonTerminatingError(serviceController, exception, "CouldNotResumeServiceNotSupported", ServiceResources.CouldNotResumeServiceNotSupported, ErrorCategory.CloseError); } } else { base.WriteNonTerminatingError(serviceController, exception, "CouldNotResumeServiceNotRunning", ServiceResources.CouldNotResumeServiceNotRunning, ErrorCategory.CloseError); } base.WriteNonTerminatingError(serviceController, exception, "CouldNotResumeService", ServiceResources.CouldNotResumeService, ErrorCategory.CloseError); return false; } }
public void ExecuteCommand_Service_ContinuePending () { 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.Continue (); sc.ExecuteCommand (128); try { sc.ExecuteCommand (127); Assert.Fail ("#C1"); } catch (InvalidOperationException ex) { // Cannot control Schedule service on computer '.' Assert.AreEqual (typeof (InvalidOperationException), ex.GetType (), "#C2"); Assert.IsNotNull (ex.Message, "#C3"); Assert.IsTrue (ex.Message.IndexOf ("Schedule") != -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"); }
private bool ContinueService(Service serviceController) { if (serviceController.Status == ServiceControllerStatus.Running) { return true; // already running } if (!serviceController.CanPauseAndContinue) { Log.LogError(Properties.Resources.ServiceCannotContinue, ServiceName, MachineName); return false; } if (serviceController.Status != ServiceControllerStatus.Paused) { Log.LogError(Properties.Resources.ServiceNotPaused, ServiceName, MachineName); return false; } Log.LogMessage(Properties.Resources.ServiceContinuing, DisplayName); serviceController.Continue(); // wait until service is running or timeout expired serviceController.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromMilliseconds(Timeout)); Log.LogMessage(Properties.Resources.ServiceContinued, DisplayName); return true; }
public void Constructor3 () { if (RunningOnUnix) Assert.Ignore ("Running on Unix."); ServiceController sc = new ServiceController ("lanmanworkstation", Environment.MachineName); Assert.IsTrue (sc.CanPauseAndContinue, "#A1"); Assert.IsTrue (sc.CanShutdown, "#B1"); Assert.IsTrue (sc.CanStop, "#C1"); sc.Close (); sc.Continue (); ServiceController [] dependentServices = sc.DependentServices; Assert.IsNotNull (dependentServices, "#D1"); Assert.IsTrue (dependentServices.Length > 1, "#D2"); Assert.IsNotNull (sc.DisplayName, "#E1"); Assert.AreEqual ("Workstation", sc.DisplayName, "#E2"); Assert.IsNotNull (sc.MachineName, "#F1"); Assert.AreEqual (Environment.MachineName, sc.MachineName, "#F2"); sc.Refresh (); Assert.IsNotNull (sc.ServiceName, "#G1"); Assert.AreEqual ("lanmanworkstation", sc.ServiceName, "#G2"); ServiceController [] servicesDependedOn = sc.ServicesDependedOn; Assert.IsNotNull (servicesDependedOn, "#H1"); Assert.AreEqual (0, servicesDependedOn.Length, "#H2"); Assert.AreEqual (ServiceType.Win32ShareProcess, sc.ServiceType, "#I1"); Assert.AreEqual (ServiceControllerStatus.Running, sc.Status, "#J1"); }
public static async Task<bool> ContinueService( [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: return true; case ServiceControllerStatus.ContinuePending: case ServiceControllerStatus.StartPending: return await WaitForAsync(controller, ServiceControllerStatus.Running, token) .ConfigureAwait(false); case ServiceControllerStatus.Paused: controller.Continue(); return await WaitForAsync(controller, ServiceControllerStatus.Running, token) .ConfigureAwait(false); case ServiceControllerStatus.PausePending: if (!await WaitForAsync(controller, ServiceControllerStatus.Paused, token) .ConfigureAwait(false)) return false; controller.Continue(); return await WaitForAsync(controller, ServiceControllerStatus.Running, token) .ConfigureAwait(false); default: return false; } } catch (TaskCanceledException) { return false; } }
private static void EnsureServiceIsRunning (ServiceController sc) { sc.Refresh (); switch (sc.Status) { case ServiceControllerStatus.ContinuePending: sc.WaitForStatus (ServiceControllerStatus.Running, new TimeSpan (0, 0, 5)); break; case ServiceControllerStatus.Paused: sc.Continue (); sc.WaitForStatus (ServiceControllerStatus.Running, new TimeSpan (0, 0, 5)); break; case ServiceControllerStatus.PausePending: sc.WaitForStatus (ServiceControllerStatus.Paused, new TimeSpan (0, 0, 5)); sc.Continue (); sc.WaitForStatus (ServiceControllerStatus.Running, new TimeSpan (0, 0, 5)); break; case ServiceControllerStatus.StartPending: sc.WaitForStatus (ServiceControllerStatus.Running, new TimeSpan (0, 0, 5)); break; case ServiceControllerStatus.Stopped: sc.Start (); sc.WaitForStatus (ServiceControllerStatus.Running, new TimeSpan (0, 0, 5)); break; case ServiceControllerStatus.StopPending: sc.WaitForStatus (ServiceControllerStatus.Stopped, new TimeSpan (0, 0, 5)); sc.Start (); sc.WaitForStatus (ServiceControllerStatus.Running, new TimeSpan (0, 0, 5)); break; } }
/// <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; }
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 Continue () { 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.Pause (); try { Assert.AreEqual (ServiceControllerStatus.Running, sc1.Status, "#B1"); Assert.AreEqual (ServiceControllerStatus.Running, sc2.Status, "#B2"); sc1.WaitForStatus (ServiceControllerStatus.Paused, new TimeSpan (0, 0, 5)); Assert.AreEqual (ServiceControllerStatus.Paused, sc1.Status, "#C1"); Assert.AreEqual (ServiceControllerStatus.Running, sc2.Status, "#C2"); sc1.Continue (); Assert.AreEqual (ServiceControllerStatus.Paused, sc1.Status, "#D1"); Assert.AreEqual (ServiceControllerStatus.Running, sc2.Status, "#D2"); sc1.WaitForStatus (ServiceControllerStatus.Running, new TimeSpan (0, 0, 5)); Assert.AreEqual (ServiceControllerStatus.Running, sc1.Status, "#E1"); Assert.AreEqual (ServiceControllerStatus.Running, sc2.Status, "#E2"); } finally { EnsureServiceIsRunning (sc1); sc2.Refresh (); } }
public void RestartService(string serviceName, int timeoutMilliseconds) { var sEvent = "Restarting Service, Service Name: " + serviceName + " Time: " + DateTime.Now.ToString(); var sType = EventLogEntryType.Information; var service = new ServiceController(serviceName); try { int millisec1 = Environment.TickCount; TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds); if (service.Status == ServiceControllerStatus.Running && service.CanStop) { service.Stop(); service.WaitForStatus(ServiceControllerStatus.Stopped, timeout); sEvent += "\nSuccessfully stop Service, Service Name: " + serviceName + " Time: " + DateTime.Now.ToString(); } int millisec2 = Environment.TickCount; timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds - (millisec2 - millisec1)); service.Refresh(); if (service.Status == ServiceControllerStatus.Stopped) { service.Start(); service.WaitForStatus(ServiceControllerStatus.Running, timeout); sEvent += "\nSuccessfully start Service, Service Name: " + serviceName + " Time: " + DateTime.Now.ToString(); } if (service.Status == ServiceControllerStatus.Paused) { service.Continue(); service.WaitForStatus(ServiceControllerStatus.Running, timeout); sEvent += "\nSuccessfully resume Service, Service Name: " + serviceName + " Time: " + DateTime.Now.ToString(); } } catch (Exception e) { sEvent += "\nFailed to restart Service, Service Name: " + serviceName + " Time: " + DateTime.Now.ToString(); sEvent += "\nFailed to restart Service, due to: " + e.Message + ", from: " + e.Source + ", for more: " + e.HelpLink; sType = EventLogEntryType.Error; } finally { if (!EventLog.SourceExists(SSource)) EventLog.CreateEventSource(SSource, SLog); EventLog.WriteEntry(SSource, sEvent, sType); } }
public void Continue_Machine_DoesNotExist () { if (RunningOnUnix) Assert.Ignore ("Running on Unix."); ServiceController sc = new ServiceController ("Schedule", "doesnotexist"); try { sc.Continue (); 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"); } }
private bool StartService(Service serviceController) { Log.LogMessage(Properties.Resources.ServiceStarting, DisplayName); if (serviceController.Status == ServiceControllerStatus.Paused) { serviceController.Continue(); } else { serviceController.Start(); } // wait until service is running or timeout expired serviceController.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromMilliseconds(Timeout)); Log.LogMessage(Properties.Resources.ServiceStarted, DisplayName); return true; }
public void Continue_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.Continue (); Assert.Fail ("#B1"); } catch (InvalidOperationException ex) { // Cannot resume 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"); }