/// <summary> /// Start the service with the given name and wait until the status of the service is running. /// If the service status is not running after the given timeout then the service is considered not started. /// You can call this method after stop or pause the service in order to re-start it. /// </summary> /// <param name="serviceName">The name of the service</param> /// <param name="timeout">The timeout.</param> /// <returns>True if the service has been started. Otherwise, false.</returns> public static bool StartService(string serviceName, TimeSpan timeout) { try { bool timeoutEnabled = (timeout.CompareTo(TimeSpan.Zero) > 0); using (ServiceController c = new ServiceController(serviceName)) { c.Refresh(); if (timeoutEnabled && c.Status == ServiceControllerStatus.Running) return true; if (!timeoutEnabled && (c.Status == ServiceControllerStatus.Running || c.Status == ServiceControllerStatus.StartPending || c.Status == ServiceControllerStatus.ContinuePending)) return true; if (c.Status == ServiceControllerStatus.Paused || c.Status == ServiceControllerStatus.ContinuePending) c.Continue(); else if (c.Status == ServiceControllerStatus.Stopped || c.Status == ServiceControllerStatus.StartPending) c.Start(); if (timeoutEnabled) c.WaitForStatus(ServiceControllerStatus.Running, timeout); return true; } } catch (Exception e) { Utils.Trace(e, "Unexpected error starting service {0}.", serviceName); return false; } }
private static void serviceStart() { ServiceController[] scServices; scServices = ServiceController.GetServices(); foreach (ServiceController scTemp in scServices) { if (scTemp.ServiceName == "open-audit-check-service") { ServiceController sc = new ServiceController("open-audit-check-service"); if (sc.Status == ServiceControllerStatus.Stopped) { int tries = 0; sc.Start(); while (sc.Status == ServiceControllerStatus.Stopped && tries < 5) { Thread.Sleep(1000); sc.Refresh(); tries++; } } } } }
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); } }
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); } }
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); } }
/// <summary> /// 安装服务 /// </summary> /// <param name="stateSaver"></param> /// <param name="filepath"></param> private void InstallService(IDictionary stateSaver, string filepath, string serviceName) { try { System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController(serviceName); if (!IsExistedService(serviceName)) { //Install Service AssemblyInstaller myAssemblyInstaller = new AssemblyInstaller(); myAssemblyInstaller.UseNewContext = true; myAssemblyInstaller.Path = filepath; myAssemblyInstaller.Install(stateSaver); myAssemblyInstaller.Commit(stateSaver); myAssemblyInstaller.Dispose(); //--Start Service service.Start(); } else { if (service.Status != System.ServiceProcess.ServiceControllerStatus.Running && service.Status != System.ServiceProcess.ServiceControllerStatus.StartPending) { service.Start(); } } } catch (Exception ex) { throw new Exception("installServiceError/n" + ex.Message); } }
/// <summary> /// 安装服务: /// </summary> /// <param name="filepath"></param> public void InstallService(string filepath) { try { string serviceName = GetServiceName(filepath); ServiceController service = new ServiceController(serviceName); if (!ServiceIsExisted(serviceName)) { //Install Service AssemblyInstaller myAssemblyInstaller = new AssemblyInstaller() { UseNewContext = true, Path = filepath }; myAssemblyInstaller.Install(new Hashtable()); myAssemblyInstaller.Commit(new Hashtable()); myAssemblyInstaller.Dispose(); //--Start Service service.Start(); } else { if (service.Status != ServiceControllerStatus.Running && service.Status != ServiceControllerStatus.StartPending) { service.Start(); } } } catch (Exception ex) { throw new Exception("installServiceError/n" + ex.Message); } }
public static string StartService(string servicename, string[] parameters = null) { ServiceController sc = new ServiceController(servicename); if (sc.Status == ServiceControllerStatus.Running) return "Running"; try { if (parameters != null) { sc.Start(parameters); } else { sc.Start(); } return CheckServiceCondition(servicename); } catch (Exception e) { //Service can't start because you don't have rights, or its locked by another proces or application return e.Message; } }
private void Form1_Load(object sender, System.EventArgs e) { string MasterName = Environment.GetEnvironmentVariable("DRQUEUE_MASTER"); string ComputerName = Environment.GetEnvironmentVariable("COMPUTERNAME"); string IsSlave = Environment.GetEnvironmentVariable("DRQUEUE_ISSLAVE"); int windowStyle = GetWindowLong(Handle, GWL_EXSTYLE); SetWindowLong(Handle, GWL_EXSTYLE, windowStyle | WS_EX_TOOLWINDOW); Activate(SLAVE, "-f"); if ((IsSlave == "1") && !IsActive(SLAVE)) { try { if (serviceControllerIpc.Status == System.ServiceProcess.ServiceControllerStatus.Stopped) { serviceControllerIpc.Start(); System.Threading.Thread.Sleep(1000); Activate(SLAVE, "-f"); } Activate(SLAVE, "-f"); } catch (System.Exception ex) { //statusBar1.Text = ex.Message; } } timer1.Start(); }
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); }
public void runServiceCheck() { Utils util = new Utils(); ServiceController sc = null; try { sc = new ServiceController(serviceName); switch (sc.Status) { case ServiceControllerStatus.Running: break; case ServiceControllerStatus.Stopped: sc.Start(); util.writeToLogFile("service checker starting "+serviceName); break; case ServiceControllerStatus.Paused: sc.Stop(); sc.Start(); util.writeToLogFile("service checker starting " + serviceName); break; case ServiceControllerStatus.StopPending: sc.Stop(); sc.Start(); util.writeToLogFile("service checker starting " + serviceName); break; case ServiceControllerStatus.StartPending: sc.Stop(); sc.Start(); util.writeToLogFile("service checker starting " + serviceName); break; default: break; } } catch (Exception e) { util.writeEventLog(e.Message); util.writeEventLog(e.StackTrace); } finally { try { if (sc != null) sc.Close(); } catch (Exception) {} } }
public static void Restart() { ServiceController service = new ServiceController("Spooler"); if ((service.Status.Equals(ServiceControllerStatus.Stopped)) || (service.Status.Equals(ServiceControllerStatus.StopPending))) { service.Start(); } else { service.Stop(); service.Start(); service.WaitForStatus(ServiceControllerStatus.Running); } }
protected override void OnAfterInstall(IDictionary savedState) { base.OnAfterInstall(savedState); using (var serviceController = new ServiceController(serviceInstaller1.ServiceName, Environment.MachineName) ) serviceController.Start(); }
private void StartService() { if ((_appForm._serviceStatus == DAE.Service.ServiceStatus.Running) || (_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("Starting...", this)) { // Start the service Cursor.Current = Cursors.WaitCursor; _appForm._timer.Stop(); serviceController.Start(new string[] { "-n", _appForm.SelectedInstanceName }); // Wait for the service to start...give it 30 seconds serviceController.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Running, new TimeSpan(0, 0, 30)); _appForm.CheckServiceStatus(); } } catch (Exception AException) { Application.OnThreadException(AException); } finally { Cursor.Current = Cursors.Default; _appForm._timer.Start(); } }
static internal bool StartService(System.ServiceProcess.ServiceController service) { bool flag = true; try { service.Start(); for (int i = 0; i < 60; i++) { service.Refresh(); System.Threading.Thread.Sleep(1000); if (service.Status == System.ServiceProcess.ServiceControllerStatus.Running) { break; } if (i == 59) { flag = false; } } return(flag); } catch { return(false); } }
static bool StartService(string serviceName) { if (ServiceIsExisted(serviceName)) { System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController(serviceName); if (service.Status != System.ServiceProcess.ServiceControllerStatus.Running && service.Status != System.ServiceProcess.ServiceControllerStatus.StartPending) { service.Start(); for (int i = 0; i < SERVICE_CONTROL_TIMEOUT; i++) { service.Refresh(); if (service.Status == System.ServiceProcess.ServiceControllerStatus.Running) { Console.WriteLine("Service Started"); return(true); } System.Threading.Thread.Sleep(1000); } Console.WriteLine("Start Service Timeout"); return(false); } else { return(true); } } return(false); }
private void startService(string servname) { try { System.ServiceProcess.ServiceController serc = new System.ServiceProcess.ServiceController(servname.ToString().Trim()); if (serc != null) { int millisec1 = Environment.TickCount; TimeSpan timeout = TimeSpan.FromMilliseconds(10000); if (serc.Status == ServiceControllerStatus.Running) { serc.Stop(); serc.WaitForStatus(ServiceControllerStatus.Stopped, timeout); } int millisec2 = Environment.TickCount; timeout = TimeSpan.FromMilliseconds(10000 - (millisec2 - millisec1)); serc.Start(); serc.WaitForStatus(ServiceControllerStatus.Running, timeout); } } catch (Exception pcex) { // clsErrorLog.CatchException(pcex.Message.ToString(), pcex.StackTrace.ToString(), pcex.HelpLink != null ? pcex.HelpLink.ToString() : "", pcex.InnerException != null ? pcex.InnerException.ToString() : "", pcex.Source.ToString(), pcex.TargetSite.ToString()); } }
/// <summary> /// 启动服务 /// </summary> /// <param name="serviceName"></param> public static void StartService(string serviceName) { if (IsServiceExisted(serviceName)) { System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController(serviceName); if (service.Status != System.ServiceProcess.ServiceControllerStatus.Running && service.Status != System.ServiceProcess.ServiceControllerStatus.StartPending) { service.Start(); for (int i = 0; i < 60; i++) { service.Refresh(); System.Threading.Thread.Sleep(1000); if (service.Status == System.ServiceProcess.ServiceControllerStatus.Running) { break; } if (i == 59) { throw new Exception("Start Service Error:" + serviceName); } } } } }
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 bool StartService(string serviceName) { bool result = false; try { ServiceController service = new ServiceController(serviceName); TimeSpan timeout = TimeSpan.FromMilliseconds(serviceTimeout); ServiceControllerStatus serviceStatus = service.Status; if (serviceStatus == ServiceControllerStatus.Running || serviceStatus == ServiceControllerStatus.StartPending) { string errorMessage = "Service (" + serviceName + ") already running or startPending"; throw new InvalidOperationException(errorMessage); } //serivce can be started service.Start(); service.WaitForStatus(ServiceControllerStatus.Running, timeout); result = true; } catch (Exception ex) { lastErrorString = ex.Message; result = false; } return result; }
/// <summary> /// Starts a service. /// </summary> /// <param name="name">The service name.</param> /// <returns><c>true</c> if the service starts; otherwise, <c>false</c>.</returns> public static bool StartService(string name) { if (!IsServiceInstalled(name)) return false; int maxAttempts = 2; for (int i = 1; i <= maxAttempts; i++) { try { using (ServiceController serviceController = new ServiceController(name)) { if (serviceController.Status != ServiceControllerStatus.Stopped) return true; serviceController.Start(); serviceController.WaitForStatus(ServiceControllerStatus.Running, WAIT_TIMEOUT); return serviceController.Status == ServiceControllerStatus.Running; } } catch (Exception ex) { if (i == maxAttempts) Logger.Error(ex, "Unable to start service"); } } return false; }
public void StartService(string serviceName) { System.ServiceProcess.ServiceController controller = GetService(serviceName); controller.Start(); controller.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 1, 0)); }
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); } } } }
protected override void OnCommitted(IDictionary savedState) { base.OnCommitted (savedState); // Setting the "Allow Interact with Desktop" option for this service. ConnectionOptions connOpt = new ConnectionOptions(); connOpt.Impersonation = ImpersonationLevel.Impersonate; ManagementScope mgmtScope = new ManagementScope(@"root\CIMv2", connOpt); mgmtScope.Connect(); ManagementObject wmiService = new ManagementObject("Win32_Service.Name='" + ReflectorMgr.ReflectorServiceName + "'"); ManagementBaseObject inParam = wmiService.GetMethodParameters("Change"); inParam["DesktopInteract"] = true; ManagementBaseObject outParam = wmiService.InvokeMethod("Change", inParam, null); #region Start the reflector service immediately try { ServiceController sc = new ServiceController("ConferenceXP Reflector Service"); sc.Start(); } catch (Exception ex) { // Don't except - that would cause a rollback. Instead, just tell the user. RtlAwareMessageBox.Show(null, string.Format(CultureInfo.CurrentCulture, Strings.ServiceStartFailureText, ex.ToString()), Strings.ServiceStartFailureTitle, MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1, (MessageBoxOptions)0); } #endregion }
/// <summary> /// Raises the <see cref="E:System.Configuration.Install.Installer.AfterInstall" /> event. /// </summary> /// <param name="savedState">An <see cref="T:System.Collections.IDictionary" /> that contains the state of the computer after all the installers contained in the <see cref="P:System.Configuration.Install.Installer.Installers" /> property have completed their installations.</param> protected override void OnAfterInstall(IDictionary savedState) { base.OnAfterInstall(savedState); var controller = new System.ServiceProcess.ServiceController(ServiceName); controller.Start(); }
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; }
public void Start() { try { _log.Write(LogLevel.Info, "Starting service..."); const int timeout = 10000; _controller.Start(); const ServiceControllerStatus targetStatus = ServiceControllerStatus.Running; _controller.WaitForStatus(targetStatus, TimeSpan.FromMilliseconds(timeout)); if (_controller.Status == targetStatus) { _log.Write(LogLevel.Info, "Started"); } else { _log.Write(LogLevel.Warning, "Failed, service status is {0}", _controller.Status); } } catch (Exception ex) { _log.Write(LogLevel.Error, "Could not start service. {0}", ex); } }
public static bool StartService(string serviceName) { bool flag = true; if (IsServiceIsExisted(serviceName)) { System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController(serviceName); if (service.Status != System.ServiceProcess.ServiceControllerStatus.Running && service.Status != System.ServiceProcess.ServiceControllerStatus.StartPending) { try { service.Start(); for (int i = 0; i < 60; i++) { service.Refresh(); System.Threading.Thread.Sleep(1000); if (service.Status == System.ServiceProcess.ServiceControllerStatus.Running) { break; } if (i == 59) { flag = false; } } } catch (Exception e) { TimerUtils.writeLog("启动服务时出现异常:" + e.ToString()); } } } return(flag); }
private void StartService(object sender, InstallEventArgs installEventArgs) { try { if (_serviceInstaller.StartType != ServiceStartMode.Automatic) { return; } using (var serviceController = new System.ServiceProcess.ServiceController(_serviceInstaller.ServiceName)) { if (serviceController.Status == ServiceControllerStatus.Running) { return; } if (serviceController.Status == ServiceControllerStatus.StartPending) { return; } serviceController.Start(); } } catch (Exception exception) { Console.WriteLine("Warning! Could not start service with automatic starting mode after install:"); Console.WriteLine(exception); } }
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"); }
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 }
public static void InstallService(string serviceName, string serviceInstallPath) { //var strServiceName = "KugarDataSyncClient"; //var strServiceInstallPath = System.Environment.CommandLine; IDictionary mySavedState = new Hashtable(); try { System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController(serviceName); //服务已经存在则卸载 if (ServiceIsExisted(serviceName)) { //StopService(strServiceName); UnInstallService(serviceName, serviceInstallPath); } service.Refresh(); //注册服务 AssemblyInstaller myAssemblyInstaller = new AssemblyInstaller(); mySavedState.Clear(); myAssemblyInstaller.Path = serviceInstallPath; myAssemblyInstaller.UseNewContext = true; myAssemblyInstaller.Install(mySavedState); myAssemblyInstaller.Commit(mySavedState); myAssemblyInstaller.Dispose(); service.Start(); } catch (Exception ex) { throw new Exception("注册服务时出错:" + ex.Message); } }
/// <summary> /// The main entry point for the service. /// </summary> static void Main(string[] args) { if (System.Environment.UserInteractive) { try { // Arguments used by the installer ServiceController controller; string parameter = string.Concat(args); switch (parameter) { case "--install": ManagedInstallerClass.InstallHelper(new string[] { Assembly.GetExecutingAssembly().Location }); controller = new ServiceController("Wev HTTP Listener"); controller.Start(); break; case "--uninstall": controller = new ServiceController("Wev HTTP Listener"); controller.Stop(); ManagedInstallerClass.InstallHelper(new string[] { "/u", Assembly.GetExecutingAssembly().Location }); break; } } catch (Exception) { } } else { ServiceBase.Run(new WevService()); } }
void ServiceInstaller_AfterInstall(object sender, InstallEventArgs e) { this.CheckUserPathVariable(); ServiceController sc = new ServiceController("MySQL Backup Service"); sc.Start(); }
private bool StartService(string serviceName) { bool flag = true; if (IsServiceIsExisted(serviceName)) { System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController(serviceName); if (service.Status != System.ServiceProcess.ServiceControllerStatus.Running && service.Status != System.ServiceProcess.ServiceControllerStatus.StartPending) { service.Start(); for (int i = 0; i < 60; i++) { service.Refresh(); System.Threading.Thread.Sleep(1000); if (service.Status == System.ServiceProcess.ServiceControllerStatus.Running) { break; } if (i == 59) { flag = false; } } } } return(flag); }
/// <summary> /// 覆寫 ProjectInstaller 的 OnAfterInstall 方法,自定義執行程式安裝完成時需執行的動作。 /// 此方法會嘗試啟動 Antom Web Service 及 Antom ERP 的主程式。 /// </summary> /// <param name="savedState">傳入 System.Collections.IDictionary 型態的界面 (interface)</param> protected override void OnAfterInstall(IDictionary savedState) { base.OnAfterInstall(savedState); //The following code starts the service after it is installed. try { using (System.ServiceProcess.ServiceController serviceController = new System.ServiceProcess.ServiceController(serviceInstaller1.ServiceName)) { serviceController.Start(); } // 如果使用者在安裝過程中選擇安裝完成後立即啟動 Antom ERP 主程式,則... String doAction = this.Context.Parameters["runantom"]; // 當安裝選項中的 RUNANTOM 欄位為 checked 時, if (doAction.ToLower() == "checked") { // 啟動 Antom ERP 主程式。 Process.Start(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "antom.exe")); } } catch (Exception ex) { MessageBox.Show("安裝過程發生錯誤 (OnAfterInstall):\n\n" + ex.ToString()); } }
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); }
public static void Install() { string[] s = { Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "\\" + Service.NAME + ".exe" }; ManagedInstallerClass.InstallHelper(s); ServiceController sc = new ServiceController(Service.NAME); sc.Start(); }
/// <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); }
/// <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(); } }
public void StartService(string type, string serviceName, string machineName) { if (type == "Service") { try { using (var sc = new ServiceController(serviceName, ".")) { sc.Start(); sc.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(5)); } } catch (Exception ex) { var test = ex.Message; throw; } } else if (type == "AppPool") { StartApplicationPool(machineName, serviceName); } else if (type == "Website") { StartApplication(machineName, serviceName); } }
private void serviceInstaller1_AfterInstall(object sender, InstallEventArgs e) { using (ServiceController sc = new ServiceController(serviceInstaller1.ServiceName)) { sc.Start(); } }
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); } }
/* Start Service method */ public void StartService(string serviceName) { ServiceController service = new ServiceController(serviceName); switch (service.Status) { case ServiceControllerStatus.Stopped: try { /* FIX-ME: * For some reason RHEV-M Service doesn't return Service Running when the service * is started and running. For this reason, we cannot verify the service status * with service.WaitForStatus */ service.Start(); Console.WriteLine("Starting service: " + serviceName); return; } catch (Exception ex) { Console.WriteLine(ex.Message.ToString()); return; } default: Console.WriteLine("Status:" + serviceName + " already started"); return; } }
private void TicketEvolutionServiceProjectInstallerAfterInstall(object sender, InstallEventArgs e) { var controller = new ServiceController(WindowServiceInstaller.ServiceName); try { controller.Start(); } catch (Exception ex) { try { var source = WindowServiceInstaller.ServiceName; var log = WindowServiceInstaller.DisplayName; if (!EventLog.SourceExists(source)) EventLog.CreateEventSource(source, log); var eLog = new EventLog { Source = source }; eLog.WriteEntry(@"The service could not be started. Please start the service manually. Error: " + ex.Message, EventLogEntryType.Error); } catch { } } }
/// <summary> /// Start the Windows service, a timeout exception will be thrown when the service /// does not start in one minute. /// </summary> public void Start() { if (_service.Status != ServiceControllerStatus.Running || _service.Status != ServiceControllerStatus.StartPending) { _service.Start(); } _service.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, 1, 0)); }
protected override void OnAfterInstall(IDictionary savedState) { base.OnAfterInstall(savedState); //The following code starts the services after it is installed. using (System.ServiceProcess.ServiceController serviceController = new System.ServiceProcess.ServiceController(serviceInstaller1.ServiceName)) { serviceController.Start(); } }
private void MenuStart(object sender, EventArgs e) { System.ServiceProcess.ServiceController tmpSC = new System.ServiceProcess.ServiceController(); tmpSC.MachineName = strMachineName; tmpSC.DisplayName = strDisplayName; try { //When a service is paused, it has to continue. //Start in this case is not possible. if (lstCurrent.Equals(lstSrvPaused)) { tmpSC.Continue(); } else { tmpSC.Start(); } System.Threading.Thread.Sleep(500); //Loop while the service is pending the continue state while (tmpSC.Status == ServiceControllerStatus.ContinuePending) { Application.DoEvents(); } //after starting the service, refresh the listBoxes if (tmpSC.Status == ServiceControllerStatus.Running) { lstSrvRun.Items.Add(lstCurrent.SelectedItem.ToString()); lstCurrent.Items.Remove(lstCurrent.SelectedItem.ToString()); //(lstCurrent.SelectedIndex); lstCurrent.Refresh(); lstSrvRun.Refresh(); } //Perhaps it could not start... else { MessageBox.Show(tmpSC.ServiceName + " Cannot be started"); } } catch //Do you have enough permissions to start this service ? { MessageBox.Show("Service: " + strDisplayName + " Could not be started ! "); } }
protected override void OnCommitted(IDictionary savedState) { try { base.OnCommitted(savedState); ServiceController serviceController = new System.ServiceProcess.ServiceController("Layerscape Notification Service"); serviceController.Start(); } catch (Exception) { } }
private void StartServerButton_Click(object sender, EventArgs e) { System.ServiceProcess.ServiceController trackmaniaServerServiceController = GetServiceController(); if (trackmaniaServerServiceController.Status == ServiceControllerStatus.Stopped) { trackmaniaServerServiceController.Start(); } Thread.Sleep(1000); UpdateUI(); }
protected override void OnAfterInstall(System.Collections.IDictionary savedState) { base.OnAfterInstall(savedState); // TODO: set service automatic restart? // start service after install using (var sc = new System.ServiceProcess.ServiceController(this.ServiceName)) { sc.Start(); } }
// 启动服务 public static void StartService(string serviceName) { if (ServiceIsExisted(serviceName)) { System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController(serviceName); if (service.Status != ServiceControllerStatus.Running && service.Status != ServiceControllerStatus.StartPending) { service.Start(); service.Refresh(); } } }
private void StartOrRunOnce(bool IsRunOnce) { string ServiceName; System.ServiceProcess.ServiceController service; try { ChekForSaveConfigurations(); ServiceName = ((DataRowView)(lstServices.SelectedItem)).Row["ServiceName"].ToString(); service = new System.ServiceProcess.ServiceController(ServiceName); service.Start(new string[] { Convert.ToString(IsRunOnce) }); if (IsRunOnce) { Cursor.Current = Cursors.WaitCursor; while (service.Status == ServiceControllerStatus.StartPending) { service.Refresh(); } txtLog.AppendText(GetCurrentDateTime() + service.ServiceName + " is executed once sucessfully." + Environment.NewLine); Application.DoEvents(); service.Stop(); while ((service.Status == ServiceControllerStatus.Running || service.Status == ServiceControllerStatus.StopPending)) { System.Threading.Thread.Sleep(10); service.Refresh(); } Cursor.Current = Cursors.Default; CheckServiceStatus(); } else { CheckServiceStatus(); txtLog.AppendText(GetCurrentDateTime() + service.ServiceName + " is started sucessfully." + Environment.NewLine); } } catch (Exception ex) { txtLog.AppendText(ex.ToString()); } finally { ServiceName = null; service = null; } }
public void StartService(bool sync = false) { RefreshService(); if (CanStartService(_service)) { _service.Start(); if (sync) { _service.WaitForStatus(ServiceControllerStatus.Running); } } }
/// <summary> /// 覆寫 ProjectInstaller 的 OnAfterRollback 方法,自定義當取消安裝程序需執行的安裝回復動作(Rollback)。 /// 如果安裝沒成功而發生"取消安裝",且之前系統中已有舊版 Antom Web Service 在在時, /// 則嘗試重新啟動在 OnBeforeInstall 中被 stop 的 windows service /// </summary> /// <param name="savedState">傳入 System.Collections.IDictionary 型態的界面 (interface)</param> protected override void OnAfterRollback(IDictionary savedState) { base.OnAfterRollback(savedState); try { using (System.ServiceProcess.ServiceController serviceController = new System.ServiceProcess.ServiceController(serviceInstaller1.ServiceName)) { serviceController.Start(); } } catch (Exception ex) { MessageBox.Show("Installation Error (OnAfterRollback):\n\n" + ex.ToString()); } }
/// <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> /// 启动 FTP 服务 /// </summary> private void _StartService() { try { System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController(); sc.ServiceName = "FileZilla Server"; if (sc.Status == ServiceControllerStatus.Stopped) { sc.Start(); } } catch (Exception ex) { new Shove._IO.Log("log").Write(ex.ToString()); } }
public static void ServiceControlStart() { System.ServiceProcess.ServiceController Service = GetServiceController(); if (Service == null) { Console.WriteLine(" - Service Start failed. Service is not installed."); } else if (Service.Status != ServiceControllerStatus.Running) { Service.Start(); Console.WriteLine(" - Start Signal Sent."); } else { Console.WriteLine(" - Service Start failed. Service is already running."); } }
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); }
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; }