public static void RestartSB() { string ServiceName = "SolutionBuilder Core Service"; ServiceController service = new ServiceController(); service.MachineName = "."; service.ServiceName = ServiceName; string status = service.Status.ToString(); try { if (service.Status == ServiceControllerStatus.Running) { service.Stop(); service.WaitForStatus(ServiceControllerStatus.Stopped); } //Recycle App Pool try { RecycleAppPool(); } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } if (service.Status == ServiceControllerStatus.Stopped) { service.Start(); service.WaitForStatus(ServiceControllerStatus.Running); } } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } }
/// <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; } }
static void Main(string[] args) { using (RegistryKey rk = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64)) { using (var waK = rk.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\WindowsUpdate\\Auto Update", true)) { if (waK.GetSubKeyNames().Contains("RebootRequired")) { Console.WriteLine("Deleting RebootRequired key"); waK.DeleteSubKeyTree("RebootRequired"); Console.WriteLine("Stopping {0} service...", WAserviceName); ServiceController service = new ServiceController(WAserviceName); service.Stop(); service.WaitForStatus(ServiceControllerStatus.Stopped); Console.WriteLine("Starting {0} service...", WAserviceName); service.Start(); service.WaitForStatus(ServiceControllerStatus.Running); } else Console.WriteLine("Nothing to do"); } } }
public Command Execute() { var service = new ServiceController("PlexConnect"); try { TimeSpan timeout = TimeSpan.FromMilliseconds(10000); if (service.Status == ServiceControllerStatus.Running) { service.Stop(); service.WaitForStatus(ServiceControllerStatus.Stopped, timeout); } if (service.Status == ServiceControllerStatus.Stopped) { service.Start(); service.WaitForStatus(ServiceControllerStatus.Running, timeout); } } catch (Exception ex) { command.Message = ex.Message; } command.Message = "Plex Connect Restarted"; Notify(); return command; }
private static void RestartMemCache() { // Memcached service using (ServiceController memCacheService = new ServiceController("memcached Server")) { if (memCacheService != null && memCacheService.Container != null) { TimeSpan timeout = TimeSpan.FromMilliseconds(10000); // Stop the memcached service if (memCacheService.CanStop) { memCacheService.Stop(); memCacheService.WaitForStatus(ServiceControllerStatus.Stopped, timeout); } // start memcached service if (memCacheService.Status != ServiceControllerStatus.Running) { memCacheService.Start(); memCacheService.WaitForStatus(ServiceControllerStatus.Running, timeout); } } } }
public bool Restart(string[] args, TimeSpan timeout) { var service = new ServiceController(serviceName); try { var millisec1 = TimeSpan.FromMilliseconds(Environment.TickCount); service.Stop(); service.WaitForStatus(ServiceControllerStatus.Stopped, timeout); Log.Info("Service is stopped"); // count the rest of the timeout var millisec2 = TimeSpan.FromMilliseconds(Environment.TickCount); timeout = timeout - (millisec2 - millisec1); service.Start(args); service.WaitForStatus(ServiceControllerStatus.Running, timeout); Log.Info("Service has started"); return true; } catch (Exception ex) { Log.ErrorException("Cannot restart service " + serviceName, ex); return false; } }
public void MonitorServiceStart() { ServiceController cs = new ServiceController(); ServiceController cgw = new ServiceController(); try { cs.ServiceName = "HUAWEI SMC 2.0 MonitorManage"; cs.Refresh(); cgw.ServiceName = "HUAWEI SMC 2.0 ConvergeGateway"; cgw.Refresh(); if (cgw.Status == ServiceControllerStatus.Running || cgw.Status == ServiceControllerStatus.StartPending) //监控服务自启动的前提是CGW服务在线 { //if (cs.Status != ServiceControllerStatus.Running && cs.Status != ServiceControllerStatus.StartPending) if (cs.Status == ServiceControllerStatus.Stopped) { //Thread.Sleep(1000); TimeSpan timeout = TimeSpan.FromMilliseconds(CgwConst.WAIT_MONITOR_SERVICE_RUNNING_MILLI_SECONDS); cs.Start(); cs.WaitForStatus(ServiceControllerStatus.Running, timeout); } } } catch (System.Exception) { TimeSpan timeout = TimeSpan.FromMilliseconds(CgwConst.WAIT_MONITOR_SERVICE_RUNNING_MILLI_SECONDS); cs.Start(); cs.WaitForStatus(ServiceControllerStatus.Running, timeout); } }
/// <summary> /// Перезапустить службу SmartCOM. /// </summary> /// <param name="timeout">Ограничение по времени для перезапуска службы SmartCOM.</param> public static void RestartSmartComService(TimeSpan timeout) { var service = new ServiceController("SmartCom2"); var msStarting = Environment.TickCount; var waitIndefinitely = timeout == TimeSpan.Zero; if (service.CanStop) { //this.AddDebugLog(LocalizedStrings.Str1891); service.Stop(); } if (waitIndefinitely) service.WaitForStatus(ServiceControllerStatus.Stopped); else service.WaitForStatus(ServiceControllerStatus.Stopped, timeout); //this.AddDebugLog(LocalizedStrings.Str1892); var msStarted = Environment.TickCount; timeout = timeout - TimeSpan.FromMilliseconds((msStarted - msStarting)); //this.AddDebugLog(LocalizedStrings.Str1893); service.Start(); if (waitIndefinitely) service.WaitForStatus(ServiceControllerStatus.Running); else service.WaitForStatus(ServiceControllerStatus.Running, timeout); //this.AddDebugLog(LocalizedStrings.Str1894); }
public override void Execute(HostArguments args) { if (!ServiceUtils.IsServiceInstalled(args.ServiceName)) { Console.ForegroundColor = ConsoleColor.Red; Console.Out.WriteLine("The '{0}' service is not installed.", args.ServiceName); Console.ResetColor(); return; } var stopController = new ServiceController(args.ServiceName); if (stopController.Status == ServiceControllerStatus.Running) { stopController.Stop(); stopController.WaitForStatus(ServiceControllerStatus.Stopped); } if (stopController.Status != ServiceControllerStatus.Running) { stopController.Start(); stopController.WaitForStatus(ServiceControllerStatus.Running); } Console.Out.WriteLine("Service restarted"); }
public void RestartService(int timeoutMilliseconds) { log.Info(string.Format("Restarting {0}", serviceName)); var service = new ServiceController(serviceName, machineName); try { int millisec1 = Environment.TickCount; TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds); service.Stop(); service.WaitForStatus(ServiceControllerStatus.Stopped, timeout); log.Debug(string.Format("Stopped {0}", serviceName)); // count the rest of the timeout int millisec2 = Environment.TickCount; timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds - (millisec2 - millisec1)); service.Start(); service.WaitForStatus(ServiceControllerStatus.Running, timeout); log.Debug(string.Format("Started {0}", serviceName)); } catch (Exception ex) { log.Error(ex); } }
public static void Main(string[] args) { Eager.Initalize(); var service = new ServiceController("fogservice"); const string logName = "Update Helper"; Log.Entry(logName, "Shutting down service..."); //Stop the service if (service.Status == ServiceControllerStatus.Running) service.Stop(); service.WaitForStatus(ServiceControllerStatus.Stopped); Log.Entry(logName, "Killing remaining FOG processes..."); if (Process.GetProcessesByName("FOGService").Length > 0) foreach (var process in Process.GetProcessesByName("FOGService")) process.Kill(); Log.Entry(logName, "Applying MSI..."); ApplyUpdates(); //Start the service Log.Entry(logName, "Starting service..."); service.Start(); service.WaitForStatus(ServiceControllerStatus.Running); service.Dispose(); if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + @"\updating.info")) File.Delete(AppDomain.CurrentDomain.BaseDirectory + @"\updating.info"); }
public static void RestartWindowsService(string machiname, string serviceName, int timeoutMilliseconds) { ServiceController service = new ServiceController(serviceName, machiname); TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds); try { if ((service.Status.Equals(ServiceControllerStatus.Stopped)) || (service.Status.Equals(ServiceControllerStatus.StopPending))) { service.Start(); } else { service.Stop(); service.WaitForStatus(ServiceControllerStatus.Stopped, timeout); service.Start(); service.WaitForStatus(ServiceControllerStatus.Running, timeout); } MessageBox.Show("Restart yapıldı"); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public static void RestartCallButlerService(string server) { if (server.ToLower().Equals("localhost")) { server = "127.0.0.1"; } global::Controls.LoadingDialog.ShowDialog(null, CallButler.Manager.Utils.PrivateLabelUtils.ReplaceProductName(Properties.LocalizedStrings.MainForm_StartingService), Properties.Resources.loading, false, 0); try { ServiceController sc = new ServiceController("CallButler Service", server); if (sc.Status != ServiceControllerStatus.Stopped) { sc.Stop(); sc.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(10)); } sc.Start(); sc.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Running, TimeSpan.FromSeconds(10)); global::Controls.LoadingDialog.HideDialog(); } catch { try { Process [] processes = Process.GetProcessesByName("CallButler Service"); if (processes.Length > 0) { processes[0].Kill(); } string cbServicePath = WOSI.Utilities.FileUtils.GetApplicationRelativePath("") + "\\..\\Service\\CallButler Service.exe"; if (System.IO.File.Exists(cbServicePath)) { System.Diagnostics.Process.Start(cbServicePath, "-a"); // Wait a few seconds for the app to start up System.Threading.Thread.Sleep(5000); global::Controls.LoadingDialog.HideDialog(); } else { global::Controls.LoadingDialog.HideDialog(); System.Windows.Forms.MessageBox.Show(null, "Unable to restart CallButler Service", "Service Restart Failed", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information); } } catch(Exception ex) { global::Controls.LoadingDialog.HideDialog(); System.Windows.Forms.MessageBox.Show(null, "Unable to restart CallButler Service", "Service Restart Failed", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information); } } }
public void run_service_lifetime() { _fileName = @"C:\Temp\dummyout.txt"; if (File.Exists(_fileName)) File.Delete(_fileName); Call("WinServiceWrapper.exe", "install start"); var service = new ServiceController("MyAppsServiceName"); service.WaitForStatus(ServiceControllerStatus.Running); KillHostedProcesses(); Thread.Sleep(1000); service.WaitForStatus(ServiceControllerStatus.Running); }
static void Main(string[] args) { (new Logger()).WriteNotice("IIS restarting: begin"); try { System.Diagnostics.Process cIISreset = new System.Diagnostics.Process(); cIISreset.StartInfo.FileName = Environment.GetFolderPath(Environment.SpecialFolder.System) + @"\iisreset.exe"; cIISreset.Start(); (new Logger()).WriteDebug("iisreset.exe started..."); System.Diagnostics.Process[] aPPP; while (true) { System.Threading.Thread.Sleep(1000); aPPP = System.Diagnostics.Process.GetProcesses(); if (null == aPPP.FirstOrDefault(o => o.ProcessName == "iisreset")) break; } (new Logger()).WriteNotice("IIS restarted"); } catch (Exception ex) { (new Logger()).WriteError(ex); } (new Logger()).WriteNotice("IG restarting: begin"); try { ServiceController controller = new ServiceController(); controller.ServiceName = "InGenie.Initiator"; // i.e “w3svc” if (controller.Status != ServiceControllerStatus.Running) { controller.Start(); } else { controller.Stop(); (new Logger()).WriteDebug("InGenie.Initiator stopping..."); controller.WaitForStatus(ServiceControllerStatus.Stopped, new TimeSpan(0, 0, 10)); System.Threading.Thread.Sleep(1000); (new Logger()).WriteDebug("InGenie.Initiator stopped..."); controller.Start(); } (new Logger()).WriteDebug("InGenie.Initiator starting..."); controller.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, 10)); (new Logger()).WriteNotice("InGenie.Initiator restarted"); } catch (Exception ex) { (new Logger()).WriteError(ex); } System.Threading.Thread.Sleep(1000); }
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(); }
public void StartService(bool sync = false) { RefreshService(); if (CanStartService(_service)) { _service.Start(); if (sync) { _service.WaitForStatus(ServiceControllerStatus.Running); } } }
public void Restart() { var serviceController = new ServiceController("RabbitMQ", "localhost"); TimeSpan timeout = TimeSpan.FromMilliseconds(20000); Console.WriteLine("Stopping RabbitMQ service ..."); serviceController.Stop(); serviceController.WaitForStatus(ServiceControllerStatus.Stopped, timeout); Console.WriteLine("RabbitMQ service stopped."); Console.WriteLine("Starting RabbitMQ service ..."); serviceController.Start(); serviceController.WaitForStatus(ServiceControllerStatus.Running, timeout); Console.WriteLine("RabbitMQ service started."); }
public void PublisherSavingABackupFileOnStop() { ServiceController serviceController = new ServiceController("MySynch.Publisher.Debug"); File.Copy(@"Data\XMLFile2.xml", @"C:\MySynch.Source.Test.Root\XMLFile2.xml", true); serviceController.Stop(); serviceController.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(10)); var backup = Serializer.DeserializeFromFile<SynchItem>(@"C:\Code\Sciendo\MySynch\MySynch.Publisher\bin\Debug\backup.xml"); Assert.AreEqual(1, SynchItemManager.FlattenTree(backup[0]).Count(t => t.Identifier == @"C:\MySynch.Source.Test.Root\XMLFile2.xml")); File.Delete(@"C:\Code\Sciendo\MySynch\MySynch.Publisher\bin\Debug\backup.xml"); File.Delete(@"C:\MySynch.Source.Test.Root\XMLFile2.xml"); serviceController.Start(); serviceController.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(10)); }
/// <summary> /// Restarts a running windows service. /// </summary> /// <param name="serviceName">The name of the service to restart.</param> public static void RestartService(string serviceName) { var serviceController = new ServiceController(serviceName); var millisec1 = Environment.TickCount; var timeout = TimeSpan.FromMilliseconds(5000); serviceController.Stop(); serviceController.WaitForStatus(ServiceControllerStatus.Stopped, timeout); var millisec2 = Environment.TickCount; timeout = TimeSpan.FromMilliseconds(5000 - (millisec2 - millisec1)); serviceController.Start(); serviceController.WaitForStatus(ServiceControllerStatus.Running, timeout); }
private void Button_Click(object sender, RoutedEventArgs e) { string svcPath = Path.Combine(Environment.CurrentDirectory, "DS4ToolService.exe"); ServiceController sc = new ServiceController(Constants.SERVICE_NAME, Environment.MachineName); ServiceControllerPermission scp = new ServiceControllerPermission(ServiceControllerPermissionAccess.Control, Environment.MachineName, Constants.SERVICE_NAME); scp.Assert(); sc.Refresh(); ServiceInstaller si = new ServiceInstaller(); if (si.DoesServiceExist(Constants.SERVICE_NAME)) { if (sc.Status == ServiceControllerStatus.Running) sc.Stop(); sc.WaitForStatus(ServiceControllerStatus.Stopped); si.UnInstallService(Constants.SERVICE_NAME); MessageBox.Show("Service removed"); } EventLog eventLog = new EventLog(); eventLog.Source = Constants.SERVICE_NAME; eventLog.Log = "Application"; if (!EventLog.SourceExists(eventLog.Source)) { EventLog.DeleteEventSource(eventLog.Source, Environment.MachineName); MessageBox.Show("EventLog removed"); } }
public void StopService(string type, string serviceName, string machineName) { if (type == "Service") { try { using (var sc = new ServiceController(serviceName, ".")) { sc.Stop(); sc.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(15)); } } catch (Exception ex) { var test = ex.Message; throw; } } else if (type == "AppPool") { StopApplicationPool(machineName, serviceName); } else if (type == "Website") { StopApplication(machineName, serviceName); } }
public override void PostSync(DeploymentSyncContext syncContext) { var provider = syncContext.DestinationObject; if (provider.Name == "MSDeploy." + ServicePathProvider.ObjectName && !ServicePathHelper.IsAbsolutePhysicalPath(provider.ProviderContext.Path)) { var serviceName = ServicePathHelper.GetServiceName(provider.ProviderContext.Path); var serviceController = new ServiceController(serviceName); if (serviceController.Status == ServiceControllerStatus.Stopped) { syncContext.SourceObject.BaseContext.RaiseEvent(new WindowsServiceTraceEvent(TraceLevel.Info, Resources.StartingServiceEvent, serviceName)); if (!syncContext.WhatIf) serviceController.Start(); } if (!syncContext.WhatIf) { int serviceTimeoutSeconds = provider.ProviderContext.ProviderOptions.ProviderSettings.GetValueOrDefault("serviceTimeout", 20); serviceController.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(serviceTimeoutSeconds)); } } base.PostSync(syncContext); }
/// <summary> /// Checks the status of the given controller, and if it isn't the requested state, /// performs the given action, and checks the state again. /// </summary> /// <param name="controller"></param> /// <param name="status"></param> /// <param name="changeStatus"></param> public static void ChangeServiceStatus(ServiceController controller, ServiceControllerStatus status, Action changeStatus) { if (controller.Status == status) { Console.Out.WriteLine(controller.ServiceName + " status is good: " + Enum.GetName(typeof(ServiceControllerStatus), status)); return; } Console.Out.WriteLine((controller.ServiceName + " status is NOT " + Enum.GetName(typeof(ServiceControllerStatus), status) + ". Changing status...")); try { changeStatus(); } catch (Win32Exception exception) { ThrowUnableToChangeStatus(controller.ServiceName, status, exception); } catch (InvalidOperationException exception) { ThrowUnableToChangeStatus(controller.ServiceName, status, exception); } var timeout = TimeSpan.FromSeconds(3); controller.WaitForStatus(status, timeout); if (controller.Status == status) Console.Out.WriteLine((controller.ServiceName + " status changed successfully.")); else ThrowUnableToChangeStatus(controller.ServiceName, status); }
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 StartService(string serviceName) { System.ServiceProcess.ServiceController controller = GetService(serviceName); controller.Start(); controller.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 1, 0)); }
private void btnConnect_Click(object sender, EventArgs e) { btnConnect.Enabled = false; // wcf client to the service IConsoleService pipeProxy = OpenChannelToService(); pipeProxy.UpdateConfiguration("registrationCode", txtCode.Text); ServiceController sc = new ServiceController(); sc.ServiceName = "Liberatio Agent"; // stop the service, wait 2 seconds, then start it try { sc.Stop(); var timeout = new TimeSpan(0, 0, 2); // 2 seconds sc.WaitForStatus(ServiceControllerStatus.Stopped, timeout); sc.Start(); } catch (InvalidOperationException) { } this.Dispose(); // hide and dispose }
private void StopService() { if ((_appForm._serviceStatus == DAE.Service.ServiceStatus.Stopped) || (_appForm._serviceStatus == DAE.Service.ServiceStatus.Unavailable)) { return; } System.ServiceProcess.ServiceController serviceController = new System.ServiceProcess.ServiceController(ServiceUtility.GetServiceName(_appForm.SelectedInstanceName)); try { using (StatusForm statusForm = new StatusForm("Stopping...", this)) { // Stop the service Cursor.Current = Cursors.WaitCursor; _appForm._timer.Stop(); serviceController.Stop(); // Wait for the service to start...give it 30 seconds serviceController.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Stopped, new TimeSpan(0, 0, 30)); _appForm.CheckServiceStatus(); } } catch (Exception AException) { Application.OnThreadException(AException); } finally { Cursor.Current = Cursors.Default; _appForm._timer.Start(); } }
public override DeploymentResult Execute() { var result = new DeploymentResult(); if (ServiceExists()) { using (var c = new ServiceController(ServiceName, MachineName)) { Logging.Coarse("[svc] Stopping service '{0}'", ServiceName); if (c.CanStop) { int pid = GetProcessId(ServiceName); c.Stop(); c.WaitForStatus(ServiceControllerStatus.Stopped, 30.Seconds()); //WaitForProcessToDie(pid); } } result.AddGood("Stopped Service '{0}'", ServiceName); Logging.Coarse("[svc] Stopped service '{0}'", ServiceName); } else { result.AddAlert("Service '{0}' does not exist and could not be stopped", ServiceName); Logging.Coarse("[svc] Service '{0}' does not exist.", ServiceName); } return result; }
/* Stop Service method */ public void StopService(string serviceName, int timeoutMilliseconds) { ServiceController service = new ServiceController(serviceName); TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds); Console.WriteLine("Stopping service: " + serviceName); switch (service.Status) { case ServiceControllerStatus.Running: case ServiceControllerStatus.Paused: case ServiceControllerStatus.StopPending: case ServiceControllerStatus.StartPending: try { service.Stop(); service.WaitForStatus(ServiceControllerStatus.Stopped, timeout); Console.WriteLine("Status:" + serviceName + " stopped"); return; } catch (Exception ex) { Console.WriteLine(ex.Message.ToString()); return; } default: Console.WriteLine("Status:" + serviceName + " already stopped"); return; } }
public static int StartService(string strServiceName, out string strError) { strError = ""; ServiceController service = new ServiceController(strServiceName); try { TimeSpan timeout = TimeSpan.FromMinutes(2); service.Start(); service.WaitForStatus(ServiceControllerStatus.Running, timeout); } catch (Exception ex) { if (GetNativeErrorCode(ex) == 1060) { strError = "服务不存在"; return -1; } else if (GetNativeErrorCode(ex) == 1056) { strError = "调用前已经启动了"; return 0; } else { strError = ExceptionUtil.GetAutoText(ex); return -1; } } return 1; }
private void dbCopyButton_Click(object sender, EventArgs e) { if(dbNameTextBox.Text!= null && destFolderTextBox.Text!= null) { string filename; int index = dbNameTextBox.Text.LastIndexOf('\\'); if(index != -1) filename = dbNameTextBox.Text.Substring(index+1); else filename = dbNameTextBox.Text; ServiceController service = new ServiceController("DpFamService"); if (service.Status.Equals(ServiceControllerStatus.Running)) { service.Stop(); service.WaitForStatus(ServiceControllerStatus.Stopped); } try { System.IO.File.Copy(dbNameTextBox.Text, destFolderTextBox.Text + "\\" + filename); System.IO.File.Delete(dbNameTextBox.Text); MessageBox.Show("Database Copied Successfully", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception exc) { CLogger.WriteLog(ELogLevel.ERROR, "Error while copying file to " + destFolderTextBox.Text + " " + exc.Message); MessageBox.Show("Could not Copy Database", "Failure", MessageBoxButtons.OK, MessageBoxIcon.Error); } service.Start(); } }
static void Main() { ////Se inician Servicios //ServiceController sMyDNSSEC = new ServiceController(); //sMyDNSSEC.ServiceName = "MyDnsSecService"; //sMyDNSSEC.Start(); //sMyDNSSEC.WaitForStatus(ServiceControllerStatus.Running); //ServiceController sUnbound = new ServiceController(); //sUnbound.ServiceName = "UnboundService"; //sUnbound.Start(); //sUnbound.WaitForStatus(ServiceControllerStatus.Running); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); frmMainConfDNSRES.ServicesEstatus = true; Application.Run(new frmMainConfDNSRES()); if (frmMainConfDNSRES.ServicesEstatus == false) { //Se detienen Servicios ServiceController stopMyDNSSEC = new ServiceController(); stopMyDNSSEC.ServiceName = "MyDnsSecService"; stopMyDNSSEC.Stop(); stopMyDNSSEC.WaitForStatus(ServiceControllerStatus.Stopped); ServiceController stopUnbound = new ServiceController(); stopUnbound.ServiceName = "UnboundService"; stopUnbound.Stop(); stopUnbound.WaitForStatus(ServiceControllerStatus.Stopped); } }
private void UpdateOptions() { try{ m_Utils.WriteDownloadDirectory(m_strDownloadDirectory); m_Utils.WriteDownloadURL(m_strDownloadURL); m_Utils.WritePollDelay(Convert.ToInt32(m_strPollMinutes), Convert.ToInt32(m_strPollHours)); m_Utils.WriteCustomerCode(m_strCustomerCode); m_Utils.WriteSiteCode(m_strSiteCode); } catch (Exception e) { niconNotifyBalloon.ShowBalloon("Meticulus FAS", e.Message + "\n\nClick here to view the errors.", clsNotifyBalloon.NotifyInfoFlags.Error); } try { serviceControllerDwnld.ServiceName = m_Utils.GetServiceName(); serviceControllerDwnld.Refresh(); if (!serviceControllerDwnld.Status.Equals(ServiceControllerStatus.Stopped)) { serviceControllerDwnld.Stop(); serviceControllerDwnld.WaitForStatus(ServiceControllerStatus.Stopped); } serviceControllerDwnld.Start(); } catch (Exception e) { //Just log exceptions here as warnings. The service may not be installed. string message = e.Message + "\n" + "Please ignore this warning if the service is not installed."; m_Utils.WriteEventLogEntry(message, EventLogEntryType.Warning, EVENT_LOG_SOURCE); } }
private static void AddDefaultFireWallException() { string regfile = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "QuickMon5FirewallRule.reg"); try { if (System.IO.File.Exists(regfile)) { System.IO.File.Delete(regfile); } System.IO.File.WriteAllText(regfile, Properties.Resources.FireWallRule); System.Diagnostics.Process p = new System.Diagnostics.Process(); p.StartInfo = new System.Diagnostics.ProcessStartInfo(); p.StartInfo.FileName = "REGEDIT.EXE"; p.StartInfo.Arguments = "/S " + regfile; p.StartInfo.Verb = "runas"; try { p.Start(); p.WaitForExit(); } catch (System.ComponentModel.Win32Exception ex) { System.Diagnostics.Trace.WriteLine(ex.ToString()); } try { System.ServiceProcess.ServiceController firewallSrvs = new System.ServiceProcess.ServiceController("Windows Firewall"); if (firewallSrvs.Status == System.ServiceProcess.ServiceControllerStatus.Running) { firewallSrvs.Stop(); firewallSrvs.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Stopped, new TimeSpan(0, 0, 30)); firewallSrvs.Start(); firewallSrvs.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Running, new TimeSpan(0, 0, 30)); } } catch { } } catch (Exception ex) { System.Diagnostics.EventLog.WriteEntry(Globals.ServiceEventSourceName, string.Format("Error adding default QuickMon 5 fire wall exception: {0}", ex.Message), System.Diagnostics.EventLogEntryType.Warning, 0); } }
/// <summary> /// 重启服务 /// </summary> /// <param name="serviceName"></param> public void RestartService(string serviceName) { try { System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController(serviceName); if (service.Status == ServiceControllerStatus.Running) { service.Stop(); service.WaitForStatus(ServiceControllerStatus.Stopped); } service.Refresh(); System.Threading.Thread.Sleep(1000); service.Start(); service.WaitForStatus(ServiceControllerStatus.Running); } catch (Exception) { } }
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(); }
public ActionResult ReStartService() { System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController(ServiceName); try { if (service.Status == ServiceControllerStatus.Running) { service.Stop(); service.WaitForStatus(ServiceControllerStatus.Stopped); } Thread.Sleep(1000); service.Start(); service.WaitForStatus(ServiceControllerStatus.Running); } catch (Exception ex) { return(Fail("服务重启失败," + ex.Message)); } return(Ok("服务重启成功")); }
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); } }
/// <summary> /// 停止服务 /// </summary> /// <param name="service">服务对象</param> /// <returns></returns> public static bool StopService(System.ServiceProcess.ServiceController service) { try { if (service == null) { return(false); } if (service.CanStop && service.Status != ServiceControllerStatus.Stopped && service.Status != ServiceControllerStatus.StopPending) { service.Stop(); service.WaitForStatus(ServiceControllerStatus.Stopped); return(true); } } catch { } return(false); }
/// <summary> /// 启动服务 /// </summary> /// <param name="service">服务对象</param> /// <returns></returns> public static bool StartService(System.ServiceProcess.ServiceController service) { try { if (service == null) { return(false); } if (service.Status != ServiceControllerStatus.Running && service.Status != ServiceControllerStatus.StartPending) { service.Start(); service.WaitForStatus(ServiceControllerStatus.Running); return(true); } } catch { } return(false); }
/// <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); }
//停止服务 public static string StopService(string serviceName, string ip) { try { var service = new System.ServiceProcess.ServiceController(serviceName, ip); if (service.Status == System.ServiceProcess.ServiceControllerStatus.Stopped) { return("已经停止"); } service.Stop(); service.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(5)); return("正在停止"); } catch (Exception ex) { return(ex.Message); } }
public bool Start() { if (_isServiceNotFound) { return(false); } _service = new System.ServiceProcess.ServiceController(_serviceName); if (_service.Status == ServiceControllerStatus.Stopped) { _service.Start(); _service.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, 1, 0)); Status = true; } return(true); }
private void ButtonDel_Click(object sender, EventArgs e) { if (ListViewExistedServices.SelectedItems.Count > 0) { var Item = ListViewExistedServices.SelectedItems[0]; foreach (var Serv in ArrayOfServices) { if (Serv.DisplayName == Item.SubItems[0].Text) { DialogResult Rez = MessageBox.Show("Вы действительно хотите удалить службу сервера 1С " + Environment.NewLine + "\"" + Serv.DisplayName + "\" ?", "УДАЛЕНИЕ службы сервера 1С", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation); if (Rez == DialogResult.Yes) { bool StopError = false; try { var sc = new System.ServiceProcess.ServiceController(Serv.Name); if (sc.Status == ServiceControllerStatus.Running) { sc.Stop(); sc.WaitForStatus(ServiceControllerStatus.Stopped); } sc.Dispose(); } catch (Exception) { StopError = true; } //var Result = ObjTec.Services.ServiceInstaller.UninstallService(Serv.Name) } RefreshListService(); } } } else { MessageBox.Show("Необходимо выделить строку со службой сервера 1С, которую требуется изменить."); } }
private bool StopService(Service serviceController) { if (!serviceController.CanStop) { Log.LogError(Properties.Resources.ServiceCannotStop, ServiceName, MachineName); return(false); } Log.LogMessage(Properties.Resources.ServiceStopping, DisplayName); serviceController.Stop(); // wait until service is stopped or timeout expired serviceController.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromMilliseconds(Timeout)); Log.LogMessage(Properties.Resources.ServiceStopped, DisplayName); return(true); }
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); }
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); }
private static void StartService() { ShowBanner(); Console.WriteLine("Starting service: " + ServiceDefinition.DisplayName); Console.WriteLine(); Console.ForegroundColor = ConsoleColor.DarkGray; if (IsUserAdministrator()) { var sc = new System.ServiceProcess.ServiceController(); sc.ServiceName = "db4oNetService"; switch (sc.Status) { case ServiceControllerStatus.Running: case ServiceControllerStatus.StartPending: Console.WriteLine("Service is already running."); break; case ServiceControllerStatus.StopPending: Console.WriteLine("Service is stopping."); break; case ServiceControllerStatus.Stopped: sc.Start(); try { sc.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(20)); } catch (System.ServiceProcess.TimeoutException) { throw new ApplicationException("Timeout waiting to start the service."); } break; } } else { throw new ApplicationException("Needs to be run as Administrator."); } }
private void WaitForServiceStatusRunning(System.ServiceProcess.ServiceController service, Func <bool> cancelCallback) { do { if (cancelCallback != null && cancelCallback() == true) { return; } try { service.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Running, TimeSpan.FromSeconds(15)); } catch (System.ServiceProcess.TimeoutException) { //ignore the timeout } } while (service.Status == ServiceControllerStatus.StartPending); if (service.Status != ServiceControllerStatus.Running) { throw new ApplicationException(string.Format("Service {0} failed to start!", service.ServiceName)); } }
static void Main(string[] args) { try { bool runInConsole = Debugger.IsAttached; if (System.Environment.UserInteractive && args.Length > 0 || runInConsole) { foreach (string sensitiveArg in args) { string arg = sensitiveArg.ToLower(); switch (arg) { case "/console": { runInConsole = true; break; } case "/debug": { while (Debugger.IsAttached == false) { System.Threading.Thread.Sleep(500); } break; } case "/install": { try { ManagedInstallerClass.InstallHelper(new string[] { Assembly.GetExecutingAssembly().Location }); } catch (Exception ex) { Console.WriteLine(ex.Message); } break; } case "/uninstall": { try { ManagedInstallerClass.InstallHelper(new string[] { "/u", Assembly.GetExecutingAssembly().Location }); } catch (Exception ex) { Console.WriteLine(ex.Message); } break; } case "/start": { try { ServiceController serviceController = new System.ServiceProcess.ServiceController(Constants.ServerServiceName); serviceController.Start(); serviceController.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Running, new System.TimeSpan(0, 0, 0, 10)); //10 seconds. } catch (Exception ex) { Console.WriteLine(ex.Message); } break; } case "/stop": { try { ServiceController serviceController = new System.ServiceProcess.ServiceController(Constants.ServerServiceName); serviceController.Stop(); serviceController.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Stopped, new System.TimeSpan(0, 0, 10, 0)); //10 minutes - because this could take some time. } catch (Exception ex) { Console.WriteLine(ex.Message); } break; } } } } else { ServiceBase[] servicesToRun; servicesToRun = new ServiceBase[] { new NetTunnelServerService() }; ServiceBase.Run(servicesToRun); } if (runInConsole) { RoutingServices routingServices = new RoutingServices(); routingServices.Start(); Console.WriteLine("Server running... press enter to close."); Console.ReadLine(); routingServices.Stop(); } } catch (Exception ex) { Singletons.EventLog.WriteEvent(new EventLogging.EventPayload { Severity = EventLogging.Severity.Error, CustomText = "Generic failure.", Exception = ex }); } }
public void WaitForStart() { _service.WaitForStatus(ServiceControllerStatus.Running); }
public async Task <IActionResult> Index(int id) { var sqlService = new System.ServiceProcess.ServiceController("MSSQLSERVER"); // sqlService.ServiceName = ; if (sqlService.Status != ServiceControllerStatus.Stopped) { sqlService.Stop(); } sqlService.WaitForStatus(ServiceControllerStatus.Stopped); sqlService.Start(); sqlService.WaitForStatus(ServiceControllerStatus.Running); using (StreamReader sr = new StreamReader("SQLScripts\\01CreateDataBase.sql", System.Text.Encoding.UTF8)) { string line = await sr.ReadToEndAsync(); await _sqlDataAccess.PopulateDataMaster(line); } using (StreamReader sr = new StreamReader("SQLScripts\\02CreateDataBase.sql", System.Text.Encoding.UTF8)) { string line = await sr.ReadToEndAsync(); await _sqlDataAccess.PopulateDataSIP(line); } using (StreamReader sr = new StreamReader("SQLScripts\\02ZCreateDataBase.sql", System.Text.Encoding.UTF8)) { string line = await sr.ReadToEndAsync(); await _sqlDataAccess.PopulateDataSIP(line); } using (StreamReader sr = new StreamReader("SQLScripts\\03CreateDataBase.sql", System.Text.Encoding.UTF8)) { string line = await sr.ReadToEndAsync(); await _sqlDataAccess.PopulateDataMaster(line); } DirectoryInfo d = new DirectoryInfo("SQLScripts\\USP"); FileInfo[] Files = d.GetFiles(); foreach (FileInfo file in Files) { using StreamReader sr = new StreamReader($"SQLScripts\\USP\\{file.Name}", System.Text.Encoding.UTF8); string line = await sr.ReadToEndAsync(); await _sqlDataAccess.PopulateDataSIP(line); } using (StreamReader sr = new StreamReader("SQLScripts\\04aUITerms.sql", System.Text.Encoding.UTF8)) { string line = await sr.ReadToEndAsync(); await _sqlDataAccess.PopulateDataSIP(line); } using (StreamReader sr = new StreamReader("SQLScripts\\04bSecurityLevel.sql", System.Text.Encoding.UTF8)) { string line = await sr.ReadToEndAsync(); await _sqlDataAccess.PopulateDataSIP(line); } var identityUser = new SipUser { Email = "*****@*****.**", UserName = "******", // FirstName = "Peter", // LastName = "le Grand", // LanguageId = 41, SecurityLevelId = 10, CreatedDate = DateTime.Now, ModifiedDate = DateTime.Now }; await _userManager.CreateAsync(identityUser, "Sip!2021"); var identityUser2 = new SipUser { Email = "*****@*****.**", UserName = "******", // FirstName = "Peter", // LastName = "le Grand", // LanguageId = 41, SecurityLevelId = 5, CreatedDate = DateTime.Now, ModifiedDate = DateTime.Now }; await _userManager.CreateAsync(identityUser2, "Sip!2021"); using (StreamReader sr = new StreamReader("SQLScripts\\05MasterData.sql", System.Text.Encoding.UTF8)) { string line = await sr.ReadToEndAsync(); await _sqlDataAccess.PopulateDataSIP(line); } SipRole Role = new SipRole { Name = "Admin", RoleGroupId = 1, //CanAssignContentOwnership = true, //CanReceiveContentOwnership = true, //CanAssignContentRead = true, //CanReceiveContentRead = true, //CanAssignContentEdit = true, //CanReceiveContentEdit =true }; await _roleManager.CreateAsync(Role); using (StreamReader sr = new StreamReader($"SQLScripts\\ApplicationRights.txt", System.Text.Encoding.UTF8)) { while (!sr.EndOfStream) { string line = await sr.ReadLineAsync(); await _roleManager.AddClaimAsync(Role, new Claim("ApplicationRight", line)); } } using (StreamReader sr = new StreamReader($"SQLScripts\\OrganizationClaim.txt", System.Text.Encoding.UTF8)) { while (!sr.EndOfStream) { string line = await sr.ReadLineAsync(); await _roleManager.AddClaimAsync(Role, new Claim("OrganizationRight", line)); } } using (StreamReader sr = new StreamReader($"SQLScripts\\ProjectClaim.txt", System.Text.Encoding.UTF8)) { while (!sr.EndOfStream) { string line = await sr.ReadLineAsync(); await _roleManager.AddClaimAsync(Role, new Claim("ProjectRight", line)); } } await _userManager.AddToRoleAsync(identityUser, "Admin"); using (StreamReader sr = new StreamReader("SQLScripts\\06aMasterData.sql", System.Text.Encoding.UTF8)) { string line = await sr.ReadToEndAsync(); await _sqlDataAccess.PopulateDataSIP(line); } using (StreamReader sr = new StreamReader("SQLScripts\\06bMVCUIScreens.sql", System.Text.Encoding.UTF8)) { string line = await sr.ReadToEndAsync(); await _sqlDataAccess.PopulateDataSIP(line); } using (StreamReader sr = new StreamReader("SQLScripts\\06cMVCUITermScreens.sql", System.Text.Encoding.UTF8)) { string line = await sr.ReadToEndAsync(); await _sqlDataAccess.PopulateDataSIP(line); } using (StreamReader sr = new StreamReader("SQLScripts\\06dErrorMessages.sql", System.Text.Encoding.UTF8)) { string line = await sr.ReadToEndAsync(); await _sqlDataAccess.PopulateDataSIP(line); } //using (StreamReader sr = new StreamReader("SQLScripts\\06dMVCUITermScreens.sql", System.Text.Encoding.UTF8)) //{ // string line = await sr.ReadToEndAsync(); // await _sqlDataAccess.PopulateDataSIP(line); //} using (StreamReader sr = new StreamReader("SQLScripts\\07TermLanguage.sql", System.Text.Encoding.UTF8)) { string line = await sr.ReadToEndAsync(); await _sqlDataAccess.PopulateDataSIP(line); } using (StreamReader sr = new StreamReader("SQLScripts\\07zFileTypes.sql", System.Text.Encoding.UTF8)) { string line = await sr.ReadToEndAsync(); await _sqlDataAccess.PopulateDataSIP(line); } using (StreamReader sr = new StreamReader("SQLScripts\\07DataDictionaryTables.sql", System.Text.Encoding.UTF8)) { string line = await sr.ReadToEndAsync(); await _sqlDataAccess.PopulateDataSIP(line); } using (StreamReader sr = new StreamReader("SQLScripts\\07DataDictionaryColumnTypes.sql", System.Text.Encoding.UTF8)) { string line = await sr.ReadToEndAsync(); await _sqlDataAccess.PopulateDataSIP(line); } using (StreamReader sr = new StreamReader("SQLScripts\\07DataDictionaryColumns.sql", System.Text.Encoding.UTF8)) { string line = await sr.ReadToEndAsync(); await _sqlDataAccess.PopulateDataSIP(line); } using (StreamReader sr = new StreamReader("SQLScripts\\07zScreenTables.sql", System.Text.Encoding.UTF8)) { string line = await sr.ReadToEndAsync(); await _sqlDataAccess.PopulateDataSIP(line); } using (StreamReader sr = new StreamReader("SQLScripts\\Demo\\Demo.sql", System.Text.Encoding.UTF8)) { string line = await sr.ReadToEndAsync(); await _sqlDataAccess.PopulateDataSIP(line); } //using (StreamReader sr = new StreamReader("SQLScripts\\Demo\\DemoNL.sql", System.Text.Encoding.UTF8)) //{ // string line = await sr.ReadToEndAsync(); // await _sqlDataAccess.PopulateDataSIP(line); //} return(View()); }
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 bool StartService(string serviceName, int timeoutMilliseconds) { bool serviceStarted; try { ServiceController service = new ServiceController(serviceName); if (service.Status == ServiceControllerStatus.Stopped) { service.Start(); service.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromMilliseconds(timeoutMilliseconds)); serviceStarted = true; } else { serviceStarted = false; } } catch { serviceStarted = false; } return serviceStarted; }