public static ServiceControllerStatus GetServiceStatus(string serviceName) { System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController(serviceName); ServiceControllerStatus status = sc.Status; sc.Close(); return(status); }
/// <summary> /// Handles the Committed event of the ServiceInstaller control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.Configuration.Install.InstallEventArgs"/> instance containing the event data.</param> private void ServiceInstaller_Committed(object sender, InstallEventArgs e) { using (var service = new ServiceController(this.ServiceInstaller.ServiceName)) { service.Start(); service.WaitForStatus(ServiceControllerStatus.Running); service.Close(); } }
private void serviceInstaller1_BeforeUninstall(object sender, InstallEventArgs e) { ServiceController sc = new ServiceController("Ezector Thinkingcap FTP"); if (sc.Status == ServiceControllerStatus.Running) { sc.Stop(); sc.WaitForStatus(ServiceControllerStatus.Stopped); sc.Close(); } }
private void btnRestart_Click(object sender, RoutedEventArgs e) { ServiceStruct ss = (ServiceStruct)lv.SelectedItem; ServiceController sc = new ServiceController(ss.name); sc.Stop(); sc.WaitForStatus(ServiceControllerStatus.Stopped); sc.Start(); sc.WaitForStatus(ServiceControllerStatus.Running); sc.Close(); GetAllServices(); }
/// <summary> /// Verifies if the Window service with the given name is installed. /// </summary> /// <param name="serviceName"></param> /// <returns>true if the service is installed properly. false otherwise</returns> public static bool checkServiceInstallation(string serviceName) { bool exists = false; try { ServiceController sc = new ServiceController(serviceName); sc.Refresh(); //just a dummy call to make sure the service exists. sc.Close(); sc = null; exists = true; } catch {} return exists; }
public void Start(string serviceName) { _logger.Log(String.Format("Starting '{0}' Service ...", serviceName)); var serviceController = new ServiceController(serviceName); if (serviceController.Status == ServiceControllerStatus.Running) { _logger.Log(String.Format("'{0}' service already started.", serviceName)); return; } serviceController.Start(); serviceController.WaitForStatus(ServiceControllerStatus.Running); serviceController.Close(); _logger.Log(String.Format("Service '{0}' started and now running ...", serviceName)); }
/// <summary> /// Verifies if the Window service with the given name is installed. /// </summary> /// <param name="serviceName">Name of the service.</param> /// <returns> /// true if the service is installed properly. false otherwise /// </returns> public static bool CheckServiceInstallation(string serviceName) { bool exists = false; ServiceController sc = null; try { sc = new ServiceController(serviceName); sc.Refresh(); //just a dummy call to make sure the service exists. exists = true; } finally { if (sc != null) sc.Close(); sc = null; } return exists; }
protected override void OnBeforeUninstall(IDictionary savedState) { ServiceController service = new ServiceController(serviceInstaller.ServiceName); try { if (service.Status == ServiceControllerStatus.Running) { service.Stop(); service.WaitForStatus(ServiceControllerStatus.Stopped, new TimeSpan(0, 0, 0, 10)); service.Close(); } } finally { base.OnBeforeUninstall(savedState); } }
/// <summary> /// 执行自定义重置命令 /// </summary> /// <param name="command"></param> protected override void OnCustomCommand(int command) { if (200 != command || isTmRunning) return; isTmRunning = true; ServiceController ctrl = new ServiceController("Granity文件服务"); try { LogMessage("守护Granity文件服务", null, EventLogEntryType.Information); try { ctrl.Stop(); } catch { } Thread.Sleep(new TimeSpan(0, 1, 0)); ctrl.Start(); Thread.Sleep(new TimeSpan(0, 1, 0)); } catch { } ctrl.Close(); isTmRunning = false; }
public void Stop(string serviceName) { _logger.Log(String.Format("Stopping Service '{0}' ...", serviceName)); var serviceController = new ServiceController(serviceName); if (serviceController.Status == ServiceControllerStatus.Stopped) { _logger.Log(String.Format("Service '{0}' already stopped.", serviceName)); return; } if (!serviceController.CanStop) throw new ApplicationException( String.Format("Service '{0}' can't be stop at this time, please try again later", serviceName)); serviceController.Stop(); serviceController.WaitForStatus(ServiceControllerStatus.Stopped); serviceController.Close(); _logger.Log(String.Format("Service '{0}' successfully stopped.", serviceName)); }
private void StartStopService(bool state) { ServiceController service = new ServiceController("AlarmworkflowService"); try { if (state) { Log.Write("Starting service..."); try { service.Start(); service.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, 30)); Log.Write("Service started."); } catch (System.ServiceProcess.TimeoutException) { Log.Write("Service not started. Please check the Windows Eventlog"); } } else { Log.Write("Stopping service..."); if (service.Status == ServiceControllerStatus.Running) { service.Stop(); service.WaitForStatus(ServiceControllerStatus.Stopped); } service.Close(); Log.Write("Service stopped."); } } catch (InvalidOperationException) { // This exception is ok - it occurs if the service does not exist } }
static public string StopService(string svcName, TimeSpan timeout) { var logprefix = "StopService(" + svcName + "): "; try { var sc = new System.ServiceProcess.ServiceController(svcName); if (sc.Status != System.ServiceProcess.ServiceControllerStatus.Stopped) { // Start the service if the current status is stopped. Log(logprefix + "stopping"); try { // Start the service, and wait until its status is "Running". sc.Stop(); sc.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Stopped, timeout); // Display the current service status. Log(logprefix + "service status is now set to " + sc.Status.ToString()); } catch (System.ServiceProcess.TimeoutException) { Log(logprefix + "timeout reached (non-critical)"); } catch (InvalidOperationException) { return("Could not stop service"); } } sc.Close(); } catch (Exception ex) { Log(logprefix + "* exception: " + ex.ToString()); return("Could not access the service controller"); } return(null); }
/// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose(bool disposing) { if (disposing) { if (components != null) { components.Dispose(); } if (m_Utils.DownloadLock()) { m_Utils.DownloadUnLock(); } if (serviceControllerDwnld != null) { serviceControllerDwnld.Close(); serviceControllerDwnld.Dispose(); serviceControllerDwnld = null; } } base.Dispose(disposing); }
public void Start(string serviceName) { try { _logger.Log(String.Format("Starting '{0}' Service ...", serviceName)); var serviceController = new ServiceController(serviceName); if (serviceController.Status == ServiceControllerStatus.Running) { _logger.Log(String.Format("'{0}' service already started.", serviceName)); return; } serviceController.Start(); serviceController.WaitForStatus(ServiceControllerStatus.Running); serviceController.Close(); _logger.Log(String.Format("Service '{0}' started and now running ...", serviceName)); } catch (Exception ex) { _logger.Log(string.Format("An error occured trying to start the {0} service: {1}", serviceName, ex)); } }
public static void StopIIS() { ServiceController sc = new ServiceController("W3SVC"); if (sc.Status == ServiceControllerStatus.Running) { sc.Stop(); sc.WaitForStatus(ServiceControllerStatus.Stopped); } sc.Close(); }
/// <summary> /// 停止服务 /// </summary> /// <param name="serviceName">服务名</param> /// <returns></returns> public bool StopService(string serviceName) { bool isOK = false; SmServiceEventArgs es = new SmServiceEventArgs(); es.ServiceName = serviceName; es.ServiceOption = ServiceOptions.Stop; if (IsExisted(serviceName)) { es.CompleteState = ServiceCompleteStateType.Trying; onServiceStateChange(es); if (CanStop(serviceName)) { System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController(serviceName); if (service.Status == System.ServiceProcess.ServiceControllerStatus.Running) { try { service.Stop(); for (int i = 0; i < 30; i++) { service.Refresh(); System.Threading.Thread.Sleep(1000); if (service.Status == System.ServiceProcess.ServiceControllerStatus.Stopped) { es.CompleteState = ServiceCompleteStateType.Successfully; es.Error = null; isOK = true; break; } if (i == 30) { es.Error = new Exception("服务在控制时间内操作超时"); es.CompleteState = ServiceCompleteStateType.Timeout; } } } catch { es.Error = new Exception("服务停止失败"); es.CompleteState = ServiceCompleteStateType.UncanStop; } } service.Close(); } else { es.Error = new Exception("服务不能控制为停止"); es.CompleteState = ServiceCompleteStateType.UncanStop; } } else { es.Error = new Exception("指定的服务不存在"); es.CompleteState = ServiceCompleteStateType.NoExist; } onServiceStateChange(es); return(isOK); }
private void StartOMLEngineService() { try { ServiceController omlengineController = new ServiceController(@"OMLEngineService"); if (omlengineController.Status != ServiceControllerStatus.Running) { TimeSpan timeout = TimeSpan.FromSeconds(20); omlengineController.Start(); omlengineController.Close(); } } catch (Exception) { } }
public static void StartService(string name) { ServiceController sc = new ServiceController(name); try { if (sc != null && sc.Status == ServiceControllerStatus.Stopped) { sc.Start(); } sc.WaitForStatus(ServiceControllerStatus.Running); sc.Close(); } catch (Exception) { } }
public static void ExecuteCommand(string serviceName, ServiceCommandEnum serviceCommand) { System.ServiceProcess.ServiceController serviceController = new System.ServiceProcess.ServiceController(serviceName); switch (serviceCommand) { case ServiceCommandEnum.Start: try { Logging.Log(LogLevelEnum.Info, "Starting service"); serviceController.Start(); serviceController.WaitForStatus(ServiceControllerStatus.Running); Logging.Log(LogLevelEnum.Info, "Service started"); } catch (Exception ex) { Logging.Log(LogLevelEnum.Fatal, "Start failed: " + FileLogger.GetInnerException(ex).Message); MessageBox.Show("Could not start " + Settings.Instance.ServiceDisplayName); } break; case ServiceCommandEnum.Stop: try { Logging.Log(LogLevelEnum.Info, "Stopping service"); serviceController.Stop(); serviceController.WaitForStatus(ServiceControllerStatus.Stopped); Logging.Log(LogLevelEnum.Info, "Service stopped"); } catch (Exception ex) { Logging.Log(LogLevelEnum.Fatal, "Stop failed: " + FileLogger.GetInnerException(ex).Message); MessageBox.Show("Could not stop " + Settings.Instance.ServiceName); } break; case ServiceCommandEnum.Restart: try { Logging.Log(LogLevelEnum.Info, "Restarting service"); serviceController.Stop(); serviceController.WaitForStatus(ServiceControllerStatus.Stopped); serviceController.Start(); serviceController.WaitForStatus(ServiceControllerStatus.Running); Logging.Log(LogLevelEnum.Info, "Service restarted"); } catch (Exception ex) { Logging.Log(LogLevelEnum.Fatal, "Restart failed: " + FileLogger.GetInnerException(ex).Message); MessageBox.Show("Could not restart " + Settings.Instance.ServiceName); } break; case ServiceCommandEnum.Uninstall: try { Logging.Log(LogLevelEnum.Info, "Uninstalling service"); if (ServiceControl.ServiceStatus != ServiceControllerStatus.Running) { serviceController.Start(); serviceController.WaitForStatus(ServiceControllerStatus.Running); } serviceController.ExecuteCommand((int)ServiceCommandEnum.Uninstall); serviceController.Close(); Thread.Sleep(250); File.Delete(Settings.Instance.ServiceFile); Logging.Log(LogLevelEnum.Info, "Service uninstalled"); return; } catch (Exception ex) { Logging.Log(LogLevelEnum.Fatal, "Uninstall failed: " + FileLogger.GetInnerException(ex).Message); MessageBox.Show("Could not uninstall " + Settings.Instance.ServiceName); } break; } serviceController.Close(); }
public static void StartService(string serviceName, string serverName, int timeoutSec) { try { ServiceController service = new ServiceController(serviceName, serverName); if (service.Status == ServiceControllerStatus.Stopped || service.Status == ServiceControllerStatus.StartPending) { try { if (service.Status == ServiceControllerStatus.Stopped) { Log.Info("argustv: service {0} is stopped, so we try start it now...", serviceName); service.Start(); } service.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, timeoutSec)); } catch (Exception ex) { Log.Error("argustv: starting service {0} failed, {1}", serviceName, ex.Message); } } Log.Info("argustv: service {0} - current status: {1}", serviceName, service.Status.ToString()); service.Close(); service.Dispose(); } catch { Log.Info("argustv: service {0} not found on {1}", serviceName, serverName); } }
// Method to start the service automatically after installation private void StartIfNeeded(object sender, InstallEventArgs e) { // Do we need to do any work? if (!m_startOnInstall) return; try { TimeSpan waitTo = new TimeSpan(0, 0, m_startTimeout); // Get a handle to the service ServiceController sc = new ServiceController(base.ServiceName); // Start the service and wait for it to start sc.Start(); sc.WaitForStatus(ServiceControllerStatus.Running, waitTo); // Be good and release our handle sc.Close(); LogInstallMessage(EventLogEntryType.Information, m_logMessagePrefix + " Service Started"); } // Catch all exceptions catch (Exception ex) { LogInstallMessage(EventLogEntryType.Error, m_logMessagePrefix + ex.Message); } }
/// <summary> /// стартовать процесс /// </summary> public static StartProcessStatus StartProcess(string procName) { ServiceController sc; try { sc = new ServiceController(procName); } catch (Exception ex) { Logger.ErrorFormat("ServiceProcessManager - ошибка старта (получения статуса) процесса {0}: {1}", procName, ex); return StartProcessStatus.NotFound; } try { if (sc.Status != ServiceControllerStatus.Stopped) return StartProcessStatus.IsPending; try { sc.Start(); return StartProcessStatus.OK; } catch (Exception ex) { Logger.ErrorFormat("ServiceProcessManager - ошибка старта процесса {0}: {1}", procName, ex); return StartProcessStatus.FailedToStart; } } finally { sc.Close(); } }
private static bool TryKillProcess(string procName) { ServiceController sc; try { sc = new ServiceController(procName); } catch (Exception ex) { Logger.ErrorFormat("ServiceProcessManager - ошибка получения статуса процесса {0}: {1}", procName, ex); return false; } try { if (sc.Status == ServiceControllerStatus.Stopped) return true; if (sc.Status == ServiceControllerStatus.StartPending || sc.Status == ServiceControllerStatus.StopPending) return false; try { sc.Stop(); } catch (Exception ex) { Logger.ErrorFormat("ServiceProcessManager - ошибка останова процесса {0}: {1}", procName, ex); return false; } } finally { sc.Close(); } return true; }
/// <summary> /// 开始服务 /// </summary> /// <param name="serviceName">服务名</param> /// <returns></returns> public bool StartService(string serviceName) { bool isOK = false; SmServiceEventArgs es = new SmServiceEventArgs(); es.ServiceName = serviceName; es.ServiceOption = ServiceOptions.Start; if (IsExisted(serviceName)) { //服务存在 es.CompleteState = ServiceCompleteStateType.Trying; onServiceStateChange(es); if (GetRunType(serviceName) != ServiceStartType.Disabled) { //服务不是禁用的 System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController(serviceName); if (service.Status != ServiceControllerStatus.Running && service.Status != ServiceControllerStatus.StartPending) { //服务不是运行中的 try { service.Start(); } catch (Exception ex) { es.Error = ex; es.CompleteState = ServiceCompleteStateType.Error; onServiceStateChange(es); return(false); } for (int i = 0; i < 30; i++) { service.Refresh(); System.Threading.Thread.Sleep(1000); if (service.Status == System.ServiceProcess.ServiceControllerStatus.Running) { es.CompleteState = ServiceCompleteStateType.Successfully; es.Error = null; onServiceStateChange(es); isOK = true; break; } if (i == 30) { es.Error = new Exception("服务在控制时间内操作超时"); es.CompleteState = ServiceCompleteStateType.Timeout; isOK = true; } } } else { es.CompleteState = ServiceCompleteStateType.Successfully; es.Error = new Exception("服务已经运行"); onServiceStateChange(es); } service.Close(); } else { //服是禁用的 es.Error = new Exception("服务在禁用状态不能操作"); es.CompleteState = ServiceCompleteStateType.Disabled; onServiceStateChange(es); } } else { //服务不存在 es.Error = new Exception("指定的服务不存在"); es.CompleteState = ServiceCompleteStateType.NoExist; onServiceStateChange(es); } return(isOK); }
public static void SetServiceRecoveryOptions( string serviceName, ServiceRecoveryOptions recoveryOptions) { Exceptions.ThrowHelper.ThrowArgumentNullIfNull(serviceName, "serviceName"); Exceptions.ThrowHelper.ThrowArgumentOutOfRangeIfEmpty(serviceName, "serviceName"); Log.Debug("Setting service recovery options..."); bool requiresShutdownPriveleges = recoveryOptions.FirstFailureAction == ServiceRecoveryAction.RestartTheComputer || recoveryOptions.SecondFailureAction == ServiceRecoveryAction.RestartTheComputer || recoveryOptions.SubsequentFailureActions == ServiceRecoveryAction.RestartTheComputer; if (requiresShutdownPriveleges) { GrantShutdownPrivileges(); } const int actionCount = 3; var restartServiceAfter = (uint)TimeSpan.FromMinutes( recoveryOptions.MinutesToRestartService).TotalMilliseconds; IntPtr failureActionsPointer = IntPtr.Zero; IntPtr actionPointer = IntPtr.Zero; ServiceController controller = null; try { // Open the service controller = new ServiceController(serviceName); // Set up the failure actions var failureActions = new SERVICE_FAILURE_ACTIONS { dwResetPeriod = (int)TimeSpan.FromDays(recoveryOptions.DaysToResetFailAcount).TotalSeconds, cActions = actionCount, lpRebootMsg = recoveryOptions.RebootMessage }; // allocate memory for the individual actions actionPointer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(SC_ACTION)) * actionCount); ServiceRecoveryAction[] actions = { recoveryOptions.FirstFailureAction, recoveryOptions.SecondFailureAction, recoveryOptions.SubsequentFailureActions }; for (int i = 0; i < actions.Length; i++) { ServiceRecoveryAction action = actions[i]; var scAction = GetScAction(action, restartServiceAfter); Marshal.StructureToPtr(scAction, (IntPtr)((Int64)actionPointer + (Marshal.SizeOf(typeof(SC_ACTION))) * i), false); } failureActions.lpsaActions = actionPointer; string command = recoveryOptions.CommandToLaunchOnFailure; if (command != null) { failureActions.lpCommand = command; } failureActionsPointer = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(SERVICE_FAILURE_ACTIONS))); Marshal.StructureToPtr(failureActions, failureActionsPointer, false); // Make the change bool success = ChangeServiceConfig2( controller.ServiceHandle.DangerousGetHandle(), SERVICE_CONFIG_FAILURE_ACTIONS, failureActionsPointer); // Check that the change occurred if (!success) { throw new Win32Exception(Marshal.GetLastWin32Error(), "Unable to change the Service configuration."); } } finally { if (failureActionsPointer != IntPtr.Zero) { Marshal.FreeHGlobal(failureActionsPointer); } if (actionPointer != IntPtr.Zero) { Marshal.FreeHGlobal(actionPointer); } if (controller != null) { controller.Close(); } Log.Debug("Done setting service recovery options."); } }
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"); } }
protected override void OnBeforeUninstall(System.Collections.IDictionary savedState) { ServiceController controller = new ServiceController(Constants.ServiceName); try { if (controller.Status == ServiceControllerStatus.Running || controller.Status == ServiceControllerStatus.Paused) { controller.Stop(); controller.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(15)); controller.Close(); } } finally { base.OnBeforeUninstall(savedState); } }
public static ServiceRecoveryOptions GetServiceRecoveryOptions(string serviceName) { Exceptions.ThrowHelper.ThrowArgumentNullIfNull(serviceName, "serviceName"); Exceptions.ThrowHelper.ThrowArgumentOutOfRangeIfEmpty(serviceName, "serviceName"); Log.Debug("Getting service recovery options..."); // 8KB is the largest buffer supported by QueryServiceConfig2 const int bufferSize = 1024 * 8; IntPtr bufferPtr = IntPtr.Zero; ServiceRecoveryOptions recoveryOptions; ServiceController controller = null; try { // Open the service controller = new ServiceController(serviceName); uint dwBytesNeeded; // Allocate memory for struct bufferPtr = Marshal.AllocHGlobal(bufferSize); int queryResult = QueryServiceConfig2( controller.ServiceHandle.DangerousGetHandle(), SERVICE_CONFIG_FAILURE_ACTIONS, bufferPtr, bufferSize, out dwBytesNeeded); if (queryResult == 0) { throw new Win32Exception(Marshal.GetLastWin32Error(), "Unable to query the Service configuration."); } // Cast the buffer to a QUERY_SERVICE_CONFIG struct SERVICE_FAILURE_ACTIONS config = (SERVICE_FAILURE_ACTIONS)Marshal.PtrToStructure(bufferPtr, typeof(SERVICE_FAILURE_ACTIONS)); recoveryOptions = new ServiceRecoveryOptions { DaysToResetFailAcount = (int) TimeSpan.FromSeconds(config.dwResetPeriod).TotalDays, RebootMessage = config.lpRebootMsg, CommandToLaunchOnFailure = config.lpCommand }; int actionCount = config.cActions; if (actionCount != 0) { uint millisecondsToRestartService = 0; SC_ACTION[] actions = new SC_ACTION[actionCount]; for (int i = 0; i < config.cActions; i++) { SC_ACTION action = (SC_ACTION)Marshal.PtrToStructure( (IntPtr)(config.lpsaActions.ToInt32() + (Marshal.SizeOf(typeof(SC_ACTION)) * i)), typeof(SC_ACTION)); actions[i] = action; millisecondsToRestartService = action.Delay; } recoveryOptions.FirstFailureAction = GetServiceRecoveryAction(actions[0]); recoveryOptions.SecondFailureAction = GetServiceRecoveryAction(actions[1]); recoveryOptions.SubsequentFailureActions = GetServiceRecoveryAction(actions[2]); recoveryOptions.MinutesToRestartService = (int)TimeSpan.FromMilliseconds(millisecondsToRestartService).TotalMinutes; } } finally { // Clean up if (bufferPtr != IntPtr.Zero) { Marshal.FreeHGlobal(bufferPtr); } if (controller != null) { controller.Close(); } Log.Debug("Done getting service recovery options."); } return recoveryOptions; }
private void StopService() { var sc = new ServiceController(_Configuration.ServiceName); try { if (sc.CanStop) { if (sc.Status != ServiceControllerStatus.Stopped && sc.Status != ServiceControllerStatus.StopPending) { sc.Stop(); sc.WaitForStatus(ServiceControllerStatus.Stopped, _ServiceControllerTimeout); } } } catch (System.ServiceProcess.TimeoutException) { Console.Write(string.Format(CultureInfo.InvariantCulture, "Could not stop the {0} service.", _Configuration.ServiceName)); } finally { sc.Close(); } }
public static ActionResult StartOMLEngineService(Session session) { sessionObj = session; CustomActions.LogToSession("Inside StartOMLEngineService"); try { ServiceController omlengineController = new ServiceController(@"OMLEngineService"); TimeSpan timeout = TimeSpan.FromSeconds(20); omlengineController.Start(); omlengineController.WaitForStatus(ServiceControllerStatus.Running, timeout); omlengineController.Close(); CustomActions.LogToSession("StartOMLEngineService CA: Success"); return ActionResult.Success; } catch (Exception e) { CustomActions.LogToSession(string.Format("Error starting OMLEngineService: {0}", e.Message)); return ActionResult.Failure; } }
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 ActionResult StartOMLFWService(Session session) { sessionObj = session; try { ServiceController omlfsserviceController = new ServiceController(@"OMLFWService"); TimeSpan timeout = TimeSpan.FromSeconds(10); omlfsserviceController.Start(); omlfsserviceController.WaitForStatus(ServiceControllerStatus.Running, timeout); omlfsserviceController.Close(); } catch (Exception e) { CustomActions.LogToSession(string.Format("An error occured starting the OMLFW Service: {0}", e.Message)); return ActionResult.Failure; } return ActionResult.Success; }
public static void RestartService(String serviceName) { ServiceController sc = new ServiceController(serviceName); if (sc.Status == ServiceControllerStatus.Running) { sc.Stop(); sc.WaitForStatus(ServiceControllerStatus.Stopped); } sc.Start(); sc.WaitForStatus(ServiceControllerStatus.Running); sc.Close(); }
/// <summary> /// Attempts to start the Ingres service on the local mcachine. This static method is /// ran in a seperate thread so that the application is still usable whilst we attempt /// to start the service /// </summary> private static void StartIngresService() { ServiceController service = new ServiceController(INGRES_SERVICE_NAME); try { TimeSpan timeout = TimeSpan.FromMilliseconds(INGRES_SERVICE_OPERATION_TIMEOUT); if (service.Status == ServiceControllerStatus.Stopped) { service.Start(); } else { return; } service.WaitForStatus(ServiceControllerStatus.Running, timeout); MessageBox.Show("The Ingres service was successfully started."); } catch (TimeoutException) { MessageBox.Show( "The Ingres service failed to start in the allowed time. The service might still be in the process of starting..."); } catch (Exception) { MessageBox.Show("An error occurred attempting to start the Ingres service. "); } finally { service.Close(); } }
private void UpdateServiceUI() { if (mediaServer != null && standAloneMode == true) { serverStatus1.Text = "Serving " + mediaServer.TotalFileCount + " Files in " + mediaServer.TotalDirectoryCount + " Directories"; serverStatus2.Text = ""; UpdateDirectoriesUI(); return; } if (serviceController == null) { try { serviceController = new ServiceController("AV Media Server"); serviceStatus = serviceController.Status; } catch (System.InvalidOperationException) { serverStatus1.Text = "Media Server Service Not Installed"; serverStatus2.Text = "Use \"Standalone Mode\" for autonomous operation"; serviceController = null; serviceStatus = ServiceControllerStatus.Stopped; return; } } ServiceController serviceController2 = new ServiceController("AV Media Server"); serviceStatus = serviceController2.Status; switch (serviceStatus) { case ServiceControllerStatus.Running: if (mediaServer == null) { serverStatus1.Text = "Connecting..."; serverStatus2.Text = ""; Connect(); } else { serverStatus1.Text = "Media Server Serving "+mediaServer.TotalFileCount+" Files in "+mediaServer.TotalDirectoryCount+" Directories"; serverStatus2.Text = ""; } break; case ServiceControllerStatus.Stopped: serverStatus1.Text = "Media Server Service is Stopped"; serverStatus2.Text = ""; break; default: serverStatus1.Text = "Media Server Service is " + serviceStatus.ToString(); serverStatus2.Text = ""; break; } serviceController2.Close(); serviceController2.Dispose(); serviceController2 = null; UpdateDirectoriesUI(); }
/// <summary> /// Helper mathod to determine the state of the Ingres service. We enable the /// button to start the service if the service is stopped. Otherwise the button /// is disabled. /// </summary> private void DetermineIngresServiceState() { ServiceController service = new ServiceController(INGRES_SERVICE_NAME); try { switch (service.Status) { case ServiceControllerStatus.Stopped: this.btnStartService.Enabled = true; break; default: // disable all buttons this.btnStartService.Enabled = false; break; } } catch (Exception) { // Suppress error disable all buttons. this.btnStartService.Enabled = false; } finally { // Close the service controller to free up any resources. service.Close(); } }