private void StopService(object sender, RoutedEventArgs e) { try { string baseDirectory = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName); string scExePath = baseDirectory + @"\FolderWatchService\sc.exe"; string serviceName = @"FolderWatchService"; ////**************************************8 ProcessStartInfo procInfo = new ProcessStartInfo(); procInfo.Verb = @"runas"; procInfo.UseShellExecute = true; procInfo.FileName = scExePath; procInfo.Arguments = string.Format(@" stop {0}", serviceName); Process.Start(procInfo); ServiceController[] services = ServiceController.GetServices(); foreach (ServiceController service in services) { if (service.ServiceName == @"FolderWatchService") { ServiceControllerStatus status = service.Status; while (status != ServiceControllerStatus.Stopped) { ServiceStatusText.Content = status.ToString(); StopServiceButton.IsEnabled = false; StartServiceButton.IsEnabled = false; Thread.Sleep(1000); service.Refresh(); status = service.Status; } if (status == ServiceControllerStatus.Stopped) { ServiceStatusText.Content = status.ToString(); ServiceStatusText.Foreground = Brushes.Red; StopServiceButton.IsEnabled = false; StartServiceButton.IsEnabled = true; } else { ServiceStatusText.Content = status.ToString(); ServiceStatusText.Foreground = Brushes.Red; StopServiceButton.IsEnabled = true; StartServiceButton.IsEnabled = false; } } } //**************************************8 } catch (InvalidOperationException stopError) { MessageBox.Show(@"Error: " + stopError.InnerException.ToString()); } }
static async Task WaitForStatusAsync(ServiceControllerStatus desired, CancellationToken token) { while (true) { Func <string, bool> stateMatchesDesired; switch (desired) { case ServiceControllerStatus.Running: stateMatchesDesired = s => s == "active"; break; case ServiceControllerStatus.Stopped: stateMatchesDesired = s => s == "inactive" || s == "failed"; break; default: throw new NotImplementedException($"No handler for {desired.ToString()}"); } string[] output = await Process.RunAsync("systemctl", "-p ActiveState show iotedge", token); Log.Verbose(output.First()); if (stateMatchesDesired(output.First().Split("=").Last())) { break; } await Task.Delay(250, token).ConfigureAwait(false); } }
private void HandleServiceState(ServiceControllerStatus _status) { switch (_status) { case ServiceControllerStatus.Stopped: btnStartStopService.Content = "Start"; lblServiceState.Content = "Service stopped"; lblServiceState.Foreground = Brushes.Red; break; case ServiceControllerStatus.Running: btnStartStopService.Content = "Stop"; lblServiceState.Content = "Service started"; lblServiceState.Foreground = Brushes.Green; break; case ServiceControllerStatus.StartPending: btnStartStopService.Content = "Stop"; lblServiceState.Content = "Service starting"; lblServiceState.Foreground = Brushes.Teal; break; default: lblServiceState.Foreground = Brushes.Teal; lblServiceState.Content = "Service " + _status.ToString(); break; } }
public OperationForm(ServiceControllerStatus status) { InitializeComponent(); serviceStatusValue.Text = status.ToString(); serviceStatusValue.Image = status == ServiceControllerStatus.Running ? Properties.Resources.Ok : Properties.Resources.Warning; }
/// <summary> /// 取Win服务的状态,其中Flag: 0:未知 1:正常运行 3:停止或错误或其它或未安装此服务 /// </summary> /// <param name="_wss"></param> private void CheckWinServiceStatus(WinServiceStatus _wss) { ServiceController _sc = new ServiceController(_wss.ServiceName); try { ServiceControllerStatus st = _sc.Status; _wss.Status = st.ToString(); switch (st) { case ServiceControllerStatus.Running: _wss.Flag = 1; break; case ServiceControllerStatus.Stopped: _wss.Flag = 3; break; default: _wss.Flag = 3; break; } } catch (Exception ex) { _wss.Status = ex.Message; _wss.Flag = 3; } }
/// <summary> /// Print detailed information on a particular service. /// </summary> /// <param name="service">Service controller</param> private static void GetService(ServiceController service) { string serviceName = service.ServiceName; string displayName = service.DisplayName; ServiceControllerStatus status = service.Status; // print out detail service information Console.WriteLine(string.Format("Service Name : {0}", serviceName)); Console.WriteLine(string.Format("Display Name : {0}", displayName)); Console.WriteLine(string.Format("Service Status : {0}", status.ToString())); Console.WriteLine(string.Format("Service Type : {0}", service.ServiceType.ToString())); Console.WriteLine(string.Format("Service Can Stop : {0}", service.CanStop)); Console.WriteLine(string.Format("Service Can Pause / Continue : {0}", service.CanPauseAndContinue)); Console.WriteLine(string.Format("Service Can Shutdown : {0}", service.CanShutdown)); // print out dependent services ServiceController[] dependedServices = service.DependentServices; Console.Write(string.Format("{0} Depended Service(s) : ", dependedServices.Length.ToString())); int pos = 0; foreach (ServiceController dService in dependedServices) { Console.Write(string.Format("{0}{1}", ((dependedServices.Length > 1 && pos > 0)? ", " : string.Empty), dService.ServiceName)); pos++; } Console.WriteLine(); }
/// <summary> /// Like ServiceController.WaitForStatus, but for all services in the collection. /// </summary> /// <param name="status">See ServiceController.WaitForStatus</param> /// <param name="timeout">See ServiceController.WaitForStatus</param> public void WaitForStatus(ServiceControllerStatus status, TimeSpan timeout) { // Call WaitForStatus for all services. List <Task> tasks = this.Select(service => new Task(delegate { try { ServiceController controller = new ServiceController(service.ServiceName); controller.WaitForStatus(status, timeout); } catch (Exception e) { throw new ServiceException(service, e); } })).ToList(); tasks.ForEach(t => t.Start()); // Wait for all tasks to finish. try { Task.WaitAll(tasks.ToArray()); } catch (AggregateException e) { ServiceBase[] failed = e.InnerExceptions.Select(ie => (ie as ServiceException)?.Service).ToArray(); throw new MultiException(failed, $"Service(s) not { status.ToString().ToLower() }: { string.Join(", ", failed.Select(s => s.ServiceName)) }", typeof(TimeoutException)); } }
private static string GetLocalizedStatus(ServiceControllerStatus status) { if (status == ServiceControllerStatus.Stopped) { return(Resources.wox_plugin_service_stopped); } else if (status == ServiceControllerStatus.StartPending) { return(Resources.wox_plugin_service_start_pending); } else if (status == ServiceControllerStatus.StopPending) { return(Resources.wox_plugin_service_stop_pending); } else if (status == ServiceControllerStatus.Running) { return(Resources.wox_plugin_service_running); } else if (status == ServiceControllerStatus.ContinuePending) { return(Resources.wox_plugin_service_continue_pending); } else if (status == ServiceControllerStatus.PausePending) { return(Resources.wox_plugin_service_pause_pending); } else if (status == ServiceControllerStatus.Paused) { return(Resources.wox_plugin_service_paused); } else { return(status.ToString()); } }
private void RefreshState() { try { _svcController.Refresh(); ServiceControllerStatus status = _svcController.Status; textBoxServiceState.Text = status.ToString(); switch (status) { case ServiceControllerStatus.Stopped: buttonStartService.Enabled = true; buttonStopService.Enabled = false; break; case ServiceControllerStatus.Running: buttonStartService.Enabled = false; buttonStopService.Enabled = true; break; default: buttonStartService.Enabled = false; buttonStopService.Enabled = false; break; } } catch (Exception ex) { textBoxServiceState.Text = ex.Message; buttonStartService.Enabled = false; buttonStopService.Enabled = false; } }
private void UpdateServiceStatus() { try { if (!ServiceManager.DoesServiceExist("SmokeSignalSrvc")) { ServiceStatusLabel.Text = "Not installed!!!"; ServiceStatusLabel.ForeColor = Color.Red; } else { ServiceControllerStatus status = ServiceManager.ServiceStatus("SmokeSignalSrvc"); string s = status.ToString(); Color c = Color.Green; if (status != ServiceControllerStatus.Running) { c = Color.YellowGreen; } s += serviceConfigured ? ", configured" : ", not configured"; ServiceStatusLabel.ForeColor = c; ServiceStatusLabel.Text = s; } } finally { OnDelay.Do(UpdateServiceStatus, 5 * 1000); } }
/// <summary> /// Set status of <see cref="controlled"/> services to <see cref="WantedStatus"/> /// </summary> /// <param name="controlled"></param> /// <param name="WantedSatatus"></param> /// <returns>True - <see cref="WantedStatus"/> reached /// False - time-out expired during try</returns> public virtual bool SetServiceStatus(ServiceController controlled, ServiceControllerStatus WantedSatatus) { TimeSpan timeout = new TimeSpan(0, 1, 30); //TODO: parameter!!! bool IsStatusReached = (WantedSatatus == controlled.Status); if (!IsStatusReached) { switch (WantedSatatus) { case ServiceControllerStatus.Stopped: System.Diagnostics.Debug.Assert(controlled.CanStop, "Service " + controlled.DisplayName + " cannot be stopped"); controlled.Stop(); break; case ServiceControllerStatus.Running: controlled.Start(); break; case ServiceControllerStatus.Paused: System.Diagnostics.Debug.Assert(controlled.CanPauseAndContinue, "Service " + controlled.ServiceName + " cannot be paused\\continued"); controlled.Pause(); break; default: System.Diagnostics.Debug.Assert(false, "Unsupported Status: " + WantedSatatus); break; } // // Wait for wanted status or for the specified time-out to expire // See also try { controlled.WaitForStatus(WantedSatatus, timeout); } catch (System.ServiceProcess.TimeoutException) { log.WriteLine(LogType.Error, "HI021: " + string.Format("TIMEOUT: Service \"{0}\" failed to reach status of {1} in given time", controlled.ServiceName, WantedSatatus.ToString())); } catch (Exception objException) { log.WriteLine(LogType.Error, "HI051: " + string.Format("Service \"{0}\" failed to reach status of {1}, Error: {2} ", controlled.ServiceName, WantedSatatus.ToString(), objException.ToString())); } finally { IsStatusReached = (WantedSatatus == controlled.Status); } } return(IsStatusReached); }
public void GetServiceStatus() { using (ServiceController controller = new ServiceController(localService)) { ServiceControllerStatus serviceStatus = controller.Status; localStatus = serviceStatus.ToString(); } }
private void UpdateStatus() { ServiceController service = ServiceController.GetServices().FirstOrDefault(sc => sc.ServiceName == ServiceName); if (service == null) { lblService.Text = "Service Status: Not installed"; btnInstall.Text = "Install Service"; btnInstall.Tag = "INSTALL"; btnInstall.Enabled = (bw == null); btnStart.Text = "Start Service"; btnStart.Tag = ""; btnStart.Enabled = false; } else { btnInstall.Text = "Uninstall Service"; btnInstall.Tag = "UNINSTALL"; ServiceControllerStatus status = service.Status; lblService.Text = "Service Status: " + status.ToString(); if (status == ServiceControllerStatus.Running) { btnStart.Text = "Stop Service"; btnStart.Tag = "STOP"; btnStart.Enabled = (bw == null); btnInstall.Enabled = false; } else if (status == ServiceControllerStatus.Stopped) { btnStart.Text = "Start Service"; btnStart.Tag = "START"; btnStart.Enabled = (bw == null); btnInstall.Enabled = (bw == null); } else { btnStart.Text = "Start Service"; btnStart.Tag = ""; btnStart.Enabled = false; btnInstall.Enabled = false; } } if (service != null && servicePath == "") { servicePath = "Service path: " + GetServicePath(service.ServiceName); } bool twoStatusStrs = (!string.IsNullOrWhiteSpace(statusStr) && !string.IsNullOrWhiteSpace(statusStr)); string newStatus = statusStr + (twoStatusStrs ? Environment.NewLine : "") + servicePath; if (txtStatus.Text != newStatus) { txtStatus.Text = newStatus; } }
public string GetDisplayName(ServiceControllerStatus scs) { //Stopped string name = "已停止"; if (scs.ToString().Equals("Running")) { name = "已运行"; } return(name); }
public static string Format(ServiceControllerStatus status) { switch (status) { case ServiceControllerStatus.Running: return(Resources.GetServiceInfoRunning); case ServiceControllerStatus.Stopped: return(Resources.GetServiceInfoStopped); default: return(status.ToString().Substring(0, 1)); } }
private void btnCheckExistMSSQL_Click(object sender, EventArgs e) { bool bResult = ServiceHelper.ExistSqlServerService("MSSQLSERVER"); if (bResult == true) { ServiceControllerStatus status = ServiceHelper.GetSqlServerServiceStatus("MSSQLSERVER"); MessageDialog.ShowErrorMsgBox("MSSQLSERVER服务运行状态:" + status.ToString()); } else { MessageDialog.ShowErrorMsgBox("不存在MSSQLSERVER服务"); } }
/// <summary> /// Set button states(enabled, disabled) /// </summary> public void SetButtonStates() { if (!Visible) { return; } if (InvokeRequired) { Invoke((SetButtonStatesCallback)SetButtonStates); } else { ServiceControllerStatus serviceStatus = Program.serviceController.Status; lblCurrentStatus.Text = serviceStatus.ToString(); lblStartupMode.Text = ServiceInfo.GetSeviceStartupMode(); lblTimeStarted.Text = Program.GetServiceStartedTime(); LoadSettings(); SetStateAndLastCheck(); btnQuickCheck.Enabled = ((serviceStatus == ServiceControllerStatus.Running) && lblCurrentState.Text == "Idle"); if (imageList != null) { switch (serviceStatus) { case ServiceControllerStatus.Running: pbStatus.Image = imageList.Images[1]; btnStartStop.Text = "Stop"; btnStartStop.Enabled = true; break; case ServiceControllerStatus.Stopped: pbStatus.Image = imageList.Images[0]; btnStartStop.Text = "Start"; btnStartStop.Enabled = true; break; default: pbStatus.Image = imageList.Images[2]; btnStartStop.Text = "Paused"; btnStartStop.Enabled = false; break; } } } }
public SystemServiceStatus GetStatus() { try { ServiceControllerStatus status = Status; SystemServiceStatus systemServiceStatus; bool isInstalled = Enum.TryParse(status.ToString(), out systemServiceStatus); return(isInstalled ? (SystemServiceStatus)status : SystemServiceStatus.NotInstalled); } catch (InvalidOperationException) { return(SystemServiceStatus.NotInstalled); } }
public void StartServices(string serviceName) { try { // Get the Print Job Listner Service Status ServiceController jobListnerService = new ServiceController(serviceName); ServiceControllerStatus jobListnerServiceStatus = jobListnerService.Status; string serviceStatus = jobListnerServiceStatus.ToString(); if (serviceStatus != "Running") { jobListnerService.Start(); } } catch (Exception ex) { LogManager.RecordMessage(AUDITORSOURCE, "StartServices", LogManager.MessageType.Exception, "Failed to Start " + serviceName + "", "Restart the Configurator Service", ex.Message, ex.StackTrace); } }
/// <summary> /// Change the service status /// </summary> /// <param name="sc"></param> /// <param name="newStatus"></param> public static void RunServer(ServiceController sc, ServiceControllerStatus newStatus) { try { if (sc.Status == newStatus) { return; } // TODO: Need better waiting mechanism (ideally show a progress bar here...) // for now wait 30 seconds and confirm the new status afterward. var waitAmount = new TimeSpan(0, 0, 30); switch (newStatus) { case ServiceControllerStatus.Running: //Status("Starting server, please wait..."); sc.Start(); sc.WaitForStatus(newStatus, waitAmount); break; case ServiceControllerStatus.Stopped: //Status("Stopping server, please wait..."); sc.Stop(); sc.WaitForStatus(newStatus, waitAmount); break; default: throw new Exception("Unsupported action = " + newStatus.ToString()); } if (sc.Status != newStatus) { throw new ApplicationException("Service is not " + newStatus); } } catch (Exception ex) { Debug.WriteLine(ex.Message); throw; } }
private void Dt_Tick(object sender, EventArgs e) { usluga.Refresh(); ServiceControllerStatus stan = usluga.Status; if (stan != poprzedniStan) { ServStatus.Text = stan.ToString(); if (stan == ServiceControllerStatus.Running) { Uruchom.IsEnabled = false; Zatrzymaj.IsEnabled = true; } if (stan == ServiceControllerStatus.Stopped) { Zatrzymaj.IsEnabled = false; Uruchom.IsEnabled = true; } poprzedniStan = stan; } }
/// <summary> /// Change the service status /// </summary> /// <param name="sc"></param> /// <param name="newStatus"></param> public static void RunServer(ServiceController sc, ServiceControllerStatus newStatus) { try { if (sc.Status == newStatus) return; // TODO: Need better waiting mechanism (ideally show a progress bar here...) // for now wait 30 seconds and confirm the new status afterward. var waitAmount = new TimeSpan(0, 0, 30); switch (newStatus) { case ServiceControllerStatus.Running: //Status("Starting server, please wait..."); sc.Start(); sc.WaitForStatus(newStatus, waitAmount); break; case ServiceControllerStatus.Stopped: //Status("Stopping server, please wait..."); sc.Stop(); sc.WaitForStatus(newStatus, waitAmount); break; default: throw new Exception("Unsupported action = " + newStatus.ToString()); } if (sc.Status != newStatus) throw new ApplicationException("Service is not " + newStatus); } catch (Exception ex) { Debug.WriteLine(ex.Message); throw; } }
private void UpdateServiceStatus() { foreach (Control control in base.Controls) { if (control.Tag is ServiceInfo) { ServiceControllerStatus serviceSatus = this.GetServiceSatus(control.Controls[0].Text); (control.Controls[1] as ComboBox).SelectedItem = serviceSatus.ToString(); switch (serviceSatus) { case ServiceControllerStatus.Stopped: control.Controls[2].Enabled = true; control.Controls[3].Enabled = false; break; case ServiceControllerStatus.Running: control.Controls[2].Enabled = false; control.Controls[3].Enabled = true; break; } } } }
public override void Execute() { Logger.Debug("WindowsServiceStateCheck is checking service states..."); var failures = new List <string>(); _config.Services.ForEach( serviceName => { try { var sc = new ServiceController(serviceName, Server); var result = HealthCheckData.For(Identity, string.Format("{0} is {1}", sc.DisplayName, _config.ExpectedState)) .ResultIs(sc.Status == ExpectedState) .AddProperty("ExpectedState", ExpectedState.ToString()); var request = NotificationRequestBuilder.For(_config.NotificationMode, result, nr => { nr.DataKeyGenerator = data => string.Format("{0}>>{1}", data.CheckId, serviceName); }).Build(); Publish(request); } catch (InvalidOperationException) { failures.Add(serviceName); } }); if (failures.Count > 0) { throw new InvalidOperationException(string.Format("These services do not exist: {0}", string.Join(",", failures.ToArray()))); } }
private void HandleServiceState(ServiceControllerStatus _status) { switch (_status) { case ServiceControllerStatus.Stopped: btnStartStopService.Content = "Start"; lblServiceState.Content = "Service Stopped"; lblServiceState.Foreground = System.Windows.Media.Brushes.Red; break; case ServiceControllerStatus.Running: btnStartStopService.Content = "Stop"; lblServiceState.Content = "Service Started"; lblServiceState.Foreground = System.Windows.Media.Brushes.Green; break; case ServiceControllerStatus.StartPending: btnStartStopService.Content = "Stop"; lblServiceState.Content = "Service Starting"; lblServiceState.Foreground = System.Windows.Media.Brushes.Teal; break; default: lblServiceState.Foreground = System.Windows.Media.Brushes.Teal; lblServiceState.Content = "Service " + _status.ToString(); break; } }
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(); }
private void setServiceStatus(ServiceControllerStatus status) { if (serviceController.Status.Equals(status)) //already in the wanted status { OnProgress(processIdx + 1); } else { try { TimeSpan timeoutSec = TimeSpan.FromSeconds(timeout); bool tryAgain = false; int tryCount = 0; do { try { if (status.Equals(ServiceControllerStatus.Running)) serviceController.Start(); //TODO: support arguments else serviceController.Stop(); } catch (InvalidOperationException e) { //in some cases, the service status might be changed although the exception is thrown Thread.Sleep(TimeSpan.FromSeconds(5)); //wait a little bit time to try again serviceController.Refresh(); if (serviceController.Status.Equals(status)) //equal tryAgain = false; else if (tryCount < TOTAL_TRY) //not equal, not reach total tryAgain = true; else //when not equal to status, AND reach total try throw e; tryCount++; } } while (tryAgain); serviceController.WaitForStatus(status, timeoutSec); Console.WriteLine(serviceController.Status.ToString()); //check the status to make sure it is started properly if (serviceController.Status.Equals(status)) { OnProgress(processIdx + 1); } else { throw new InvalidOperationException(serviceController.ServiceName + " cannot be changed to status " + status.ToString()); } } //TODO: there should be configuration for the app //when error occurs to a service, should it stop or continue to next service? catch (InvalidOperationException e) { OnError(e); } catch (System.ServiceProcess.TimeoutException e) { OnError(e); } } }
private async void Update() { OneDasPerformanceInformation performanceInformation; if (!_isConnected) { return; } try { performanceInformation = await _consoleHubClient.InvokeAsync <OneDasPerformanceInformation>("GetPerformanceInformation"); lock (_syncLock_UpdateConsole) { int offset = 39; // text Console.SetCursorPosition(37 - _webServerOptions.OneDasName.Length, 2); Console.Write(_webServerOptions.OneDasName); Console.SetCursorPosition(19, 3); switch (performanceInformation.OneDasState) { case OneDasState.Run: Console.Write($"{performanceInformation.OneDasState,18}"); break; default: this.WriteColored($"{performanceInformation.OneDasState,18}", ConsoleColor.Red); break; } Console.SetCursorPosition(26, 4); this.WriteColored($"{performanceInformation.ProcessPriorityClass,11}", performanceInformation.ProcessPriorityClass == ProcessPriorityClass.RealTime ? ConsoleColor.White : ConsoleColor.Red); Console.SetCursorPosition(22, 5); ServiceControllerStatus oneDasServiceStatus = BasicBootloader.GetOneDasServiceStatus(); string text = oneDasServiceStatus == 0 ? "NotFound" : oneDasServiceStatus.ToString(); this.WriteColored($"{text,15}", oneDasServiceStatus == ServiceControllerStatus.Running ? ConsoleColor.White : ConsoleColor.Red); // numbers Console.SetCursorPosition(30 + offset, 2); Console.Write($"{performanceInformation.LateBy,5:0.0} ms"); Console.SetCursorPosition(30 + offset, 3); Console.Write($"{performanceInformation.CycleTime,5:0.0} ms"); Console.SetCursorPosition(28 + offset, 4); Console.Write($"{(int)(performanceInformation.TimerDrift / 1000),7} µs"); Console.SetCursorPosition(28 + offset, 5); Console.Write($"{performanceInformation.CpuTime,7:0} %"); Console.SetCursorPosition(0, 11); } } catch { // } }
private bool WaitForServiceStatus(ServiceController serviceController, ServiceControllerStatus status, Unlimited <EnhancedTimeSpan> maximumWaitTime, bool ignoreFailures, bool sendWatsonReportForHungService) { ExDateTime now = ExDateTime.Now; string serviceName = serviceController.ServiceName; SafeHandle safeHandle = null; try { safeHandle = serviceController.ServiceHandle; } catch (Exception e) { base.WriteVerbose(Strings.ExceptionCannotGetServiceHandle(serviceName, e)); } ExDateTime exDateTime = now; SERVICE_STATUS service_STATUS = default(SERVICE_STATUS); service_STATUS.dwCheckPoint = 0U; service_STATUS.dwWaitHint = 25000U; bool result; try { for (;;) { ExDateTime exDateTime2 = exDateTime; SERVICE_STATUS service_STATUS2 = service_STATUS; exDateTime = ExDateTime.Now; if (safeHandle != null) { if (NativeMethods.QueryServiceStatus(safeHandle, ref service_STATUS) == 0) { base.WriteError(new Win32Exception(Marshal.GetLastWin32Error()), ErrorCategory.InvalidOperation, null); } if ((ulong)service_STATUS.dwCurrentState == (ulong)((long)status)) { break; } if (service_STATUS.dwCheckPoint == service_STATUS2.dwCheckPoint) { this.WriteWarning(Strings.CheckPointNotProgressed(service_STATUS2.dwCheckPoint, service_STATUS.dwCheckPoint)); base.WriteVerbose(Strings.PreviousQueryTime(exDateTime2.ToString())); base.WriteVerbose(Strings.CurrentQueryTime(exDateTime.ToString())); if (exDateTime2.AddMilliseconds(service_STATUS2.dwWaitHint + 600000U) < exDateTime) { goto Block_9; } } else { base.WriteVerbose(Strings.CheckPointProgressed(service_STATUS2.dwCheckPoint, service_STATUS.dwCheckPoint)); } } uint num = (service_STATUS.dwWaitHint == 0U) ? 25000U : service_STATUS.dwWaitHint; try { base.WriteVerbose(Strings.WaitForServiceStatusChange(num, serviceName, status.ToString())); serviceController.WaitForStatus(status, TimeSpan.FromMilliseconds(num)); base.WriteVerbose(Strings.ServiceReachedStatusDuringWait(serviceName, status.ToString())); return(true); } catch (System.ServiceProcess.TimeoutException) { base.WriteVerbose(Strings.ServiceDidNotReachStatusDuringWait(serviceName, status.ToString(), num)); if (!maximumWaitTime.IsUnlimited && now.AddMilliseconds(maximumWaitTime.Value.TotalMilliseconds) < ExDateTime.Now) { if (!ignoreFailures) { if (sendWatsonReportForHungService) { this.SendWatsonReportForHungService(serviceName); } base.WriteError(new ServiceDidNotReachStatusException(serviceName, status.ToString()), ErrorCategory.InvalidOperation, null); } else { this.WriteWarning(Strings.ServiceDidNotReachStatus(serviceName, status.ToString())); } return(false); } } } base.WriteVerbose(Strings.ServiceReachedStatus(serviceName, status.ToString())); return(true); Block_9: if (!ignoreFailures) { if (sendWatsonReportForHungService) { this.SendWatsonReportForHungService(serviceName); } base.WriteError(new ServiceDidNotReachStatusException(serviceName, status.ToString()), ErrorCategory.InvalidOperation, null); } else { this.WriteWarning(Strings.ServiceDidNotReachStatus(serviceName, status.ToString())); } result = false; } finally { if (safeHandle != null) { safeHandle.Close(); } } return(result); }
private static bool CheckFirewallEnabled(MachineHealthContainer machineHealthContainer) { SFDeployerTrace.WriteNoise(StringResources.Info_BPAWindowsFirewall); Parallel.ForEach( machineHealthContainer.GetHealthyMachineNames(), (string machineName) => { bool result = true; try { FabricDeployerServiceController.ServiceStartupType type = FabricDeployerServiceController.GetServiceStartupType(machineName, DMConstants.FirewallServiceName); if (type == FabricDeployerServiceController.ServiceStartupType.Disabled) { SFDeployerTrace.WriteError(StringResources.Error_BPAFirewallServiceDisabled, machineName); result = false; } } catch (Exception ex) { SFDeployerTrace.WriteError(StringResources.Error_BPAFirewallServiceQueryException, machineName, ex.Message); result = false; } try { ServiceController firewallSvc = FabricDeployerServiceController.GetService(DMConstants.FirewallServiceName, machineName); ServiceControllerStatus status = firewallSvc.Status; if (status == ServiceControllerStatus.Stopped || status == ServiceControllerStatus.StopPending) { SFDeployerTrace.WriteError(StringResources.Error_BPAFirewallServiceNotRunning, machineName, status.ToString()); result = false; } } catch (Exception ex) { SFDeployerTrace.WriteError(StringResources.Error_BPAFirewallServiceStatusException, machineName, ex.Message); result = false; } if (!result) { machineHealthContainer.MarkMachineAsUnhealthy(machineName); } }); return(machineHealthContainer.EnoughHealthyMachines()); }
public string GetDisplayName(ServiceControllerStatus scs) { //Stopped string name = "已停止"; if (scs.ToString().Equals("Running")) { name = "已运行"; } return name; }
private void StartFolderWatchService() { ServiceStatusText.Content = @"Starting Service..."; try { ProcessStartInfo procInfo = new ProcessStartInfo(); procInfo.Verb = @"runas"; procInfo.UseShellExecute = true; procInfo.FileName = scExePath; string[] args = { SenderEmailAddress.Content.ToString(), SenderPassword.Password, GetRecipientsFromStackPanel(), FolderToMonitor.Content.ToString() }; procInfo.Arguments = string.Format(@" start {0} {1} {2} {3} {4}", serviceName, args[0], args[1], args[2], args[3]); try { Process.Start(procInfo); } catch (Exception) { //MessageBox.Show(@"Error: " + e.InnerException.ToString()); return; } ServiceController[] services = ServiceController.GetServices(); foreach (ServiceController service in services) { if (service.ServiceName == @"FolderWatchService") { ServiceControllerStatus status = service.Status; while (status != ServiceControllerStatus.Running) { ServiceStatusText.Content = status.ToString(); StopServiceButton.IsEnabled = false; StartServiceButton.IsEnabled = false; Thread.Sleep(1000); service.Refresh(); status = service.Status; } if (status == ServiceControllerStatus.Running) { ServiceStatusText.Content = status.ToString(); ServiceStatusText.Foreground = Brushes.Green; StopServiceButton.IsEnabled = true; StartServiceButton.IsEnabled = false; } else { ServiceStatusText.Content = status.ToString(); ServiceStatusText.Foreground = Brushes.Red; StopServiceButton.IsEnabled = false; StartServiceButton.IsEnabled = true; } } } } catch (InvalidOperationException startError) { MessageBox.Show(@"Error: " + startError.InnerException.ToString()); } }
internal static ServiceController GetServiceInStoppedState(string machineName, string serviceName, TimeSpan?timeout = null) { DeployerTrace.WriteInfo("Verifying {0} exists and is stopped", serviceName); ServiceController service = GetService(serviceName, machineName); if (service == null) { string errorMessage = string.Format(CultureInfo.InvariantCulture, "Unable to find {0} on machine {1}", serviceName, machineName); DeployerTrace.WriteError(errorMessage); throw new InvalidOperationException(errorMessage); } DeployerTrace.WriteInfo("Got service {0} on machine {1}", serviceName, machineName); // Guard against already running service ServiceControllerStatus serviceStatus = service.Status; if (serviceStatus != ServiceControllerStatus.Stopped && serviceStatus != ServiceControllerStatus.StopPending) { var timeoutTemp = timeout ?? TimeSpan.MaxValue; TimeSpan serviceStopTimeout = timeoutTemp == TimeSpan.MaxValue ? TimeSpan.FromSeconds(Constants.FabricServiceStopTimeoutInSeconds) : timeoutTemp; DeployerTrace.WriteWarning("{0} is in {1} state on machine {2} and hence trying to stop it", serviceName, serviceStatus.ToString(), machineName); service.Stop(); service.WaitForStatus(ServiceControllerStatus.Stopped, serviceStopTimeout); } serviceStatus = service.Status; if (serviceStatus != ServiceControllerStatus.Stopped) { string errorMessage = string.Format(CultureInfo.InvariantCulture, "Unable to successfully stop {0} on machine {1}", serviceName, machineName); DeployerTrace.WriteError(errorMessage); throw new InvalidOperationException(errorMessage); } DeployerTrace.WriteInfo("Service {0} is in {1} state on machine {2}", serviceName, serviceStatus.ToString(), machineName); return(service); }
private static void RunInstallerService(string machineName) { var installerSvcStartedTimeout = TimeSpan.FromMinutes(Constants.FabricInstallerServiceStartTimeoutInMinutes); TimeSpan retryInterval = TimeSpan.FromSeconds(5); int retryCount = 20; bool isLocalIp = System.Fabric.Common.Helpers.IsLocalIpAddress(machineName); Task startInstallerTask = Task.Run(() => { try { Type[] exceptionTypes = { typeof(InvalidOperationException), typeof(ComponentModel.Win32Exception) }; Helpers.PerformWithRetry(() => { // Each installerSvc handle/manager should be kept in its own thread context. Tossing this around leads to race condition failures in .NET. ServiceController installerSvc = FabricDeployerServiceController.GetService(Constants.FabricInstallerServiceName, machineName); installerSvc.WaitForStatus(ServiceControllerStatus.Running, installerSvcStartedTimeout); }, exceptionTypes, retryInterval, retryCount); DeployerTrace.WriteInfo("FabricInstallerSvc started on machine {0}", machineName); } catch (ServiceProcess.TimeoutException) { throw new ServiceProcess.TimeoutException(string.Format("Timed out waiting for Installer Service to start for machine {0}.", machineName)); } }); { ServiceController installerSvc = FabricDeployerServiceController.GetService(Constants.FabricInstallerServiceName, machineName); if (isLocalIp) { installerSvc.Start(); } else { installerSvc.Start(new string[] { Constants.FabricInstallerServiceAutocleanArg }); } } startInstallerTask.Wait(installerSvcStartedTimeout); // Locks until service is started or reaches timeout DeployerTrace.WriteInfo("Waiting for FabricInstallerService to stop after completing Fabric Uninstallation"); var waitTimeLimit = TimeSpan.FromMinutes(Constants.FabricUninstallTimeoutInMinutes); try { Type[] exceptionTypes = { typeof(InvalidOperationException), typeof(ComponentModel.Win32Exception) }; Helpers.PerformWithRetry(() => { ServiceController installerSvc = FabricDeployerServiceController.GetService(Constants.FabricInstallerServiceName, machineName); installerSvc.WaitForStatus(ServiceControllerStatus.Stopped, waitTimeLimit); }, exceptionTypes, retryInterval, retryCount); } catch (System.ServiceProcess.TimeoutException) { DeployerTrace.WriteError("FabricInstallerService Stop timed out after {0}.", waitTimeLimit.ToString()); } { ServiceController installerSvc = FabricDeployerServiceController.GetService(Constants.FabricInstallerServiceName, machineName); ServiceControllerStatus serviceStatus = installerSvc.Status; if (serviceStatus != ServiceControllerStatus.Stopped) { string errorMessage = string.Format(CultureInfo.InvariantCulture, "FabricInstallerService is in {0} state and hasn't returned to STOPPED state after uninstall timeout period", serviceStatus.ToString()); DeployerTrace.WriteError(errorMessage); throw new System.TimeoutException(errorMessage); } } }
private void MakeGUI(bool reportErrors) { #region Tab Status try { ServiceController sc = new ServiceController("gView.MapServer.Tasker"); sc.Refresh(); _serviceStatus = sc.Status; lblStatus.Text = "Service Status: " + _serviceStatus.ToString(); _installed = true; btnInstall.Text = "Uninstall Windows Service..."; switch (_serviceStatus) { case ServiceControllerStatus.Stopped: btnStart.Text = "Start Service"; btnStart.Image = global::gView.Desktop.MapServer.Admin.Properties.Resources._16_arrow_right; picStatus.Image = global::gView.Desktop.MapServer.Admin.Properties.Resources._16_square_red; break; case ServiceControllerStatus.Running: btnStart.Text = "Stop Service"; btnStart.Image = global::gView.Desktop.MapServer.Admin.Properties.Resources._16_square_red; picStatus.Image = global::gView.Desktop.MapServer.Admin.Properties.Resources._16_arrow_right; break; } btnStart.Enabled = true; btnInstall.Visible = false; ServiceStartMode mode = ServiceHelper.GetServiceStartMode("gView.MapServer.Tasker"); cmbStartType.SelectedItem = mode; } catch (Exception ex) { if (reportErrors) { MessageBox.Show(lblStatus.Text = ex.Message, "Error"); } btnStart.Enabled = false; btnInstall.Text = "Install Windows Service..."; btnInstall.Visible = true; picStatus.Image = global::gView.Desktop.MapServer.Admin.Properties.Resources._16_message_warn; } #endregion #region Tab Config btnRefreshConfig_Click(this, new EventArgs()); #endregion #region Tab Logging try { string path = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) + @"\gView.MapServer.Instance.exe.config"; XmlDocument config = new XmlDocument(); config.Load(path); XmlNode node = config.SelectSingleNode("configuration/appSettings/add[@key='log_requests']"); chkLogRequests.Enabled = (node != null); chkLogRequests.Checked = (node == null || node.Attributes["value"] == null) ? false : node.Attributes["value"].Value.ToLower() == "true"; node = config.SelectSingleNode("configuration/appSettings/add[@key='log_request_details']"); chkLogRequestDetails.Enabled = (node != null); chkLogRequestDetails.Checked = (node == null || node.Attributes["value"] == null) ? false : node.Attributes["value"].Value.ToLower() == "true"; node = config.SelectSingleNode("configuration/appSettings/add[@key='log_errors']"); chkLogErrors.Enabled = (node != null); chkLogErrors.Checked = (node == null || node.Attributes["value"] == null) ? false : node.Attributes["value"].Value.ToLower() == "true"; chkLogRequests.CheckedChanged += new EventHandler(chkLog_CheckedChanged); chkLogRequestDetails.CheckedChanged += new EventHandler(chkLog_CheckedChanged); chkLogErrors.CheckedChanged += new EventHandler(chkLog_CheckedChanged); } catch (Exception ex) { MessageBox.Show(ex.Message, "Exception"); } #endregion }