/// <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 override void Run(ServiceController[] services, Form mainForm, DataGrid serviceGrid) { var addedMachine = QuickDialog2.DoQuickDialog("Add A Machine's Services", "Machine Name:",".","Pattern ^(Enable|EPX):",""); if (addedMachine != null) { MachineName = addedMachine[0]; this.SearchPattern = addedMachine[1]; try { DataGrid dgrid = serviceGrid; this.addView = (DataView)dgrid.DataSource; CurrencyManager bm = (CurrencyManager)dgrid.BindingContext[this.addView]; ArrayList arrSelectedRows = new ArrayList(); this.addView = (DataView)bm.List; mainForm.Invoke(new InvokeDelegate(this.AddMachineInGUIThread)); serviceGrid.Refresh(); } finally { addedMachine = null; addView = null; } } }
private void MenuPause(object sender, EventArgs e) { System.ServiceProcess.ServiceController tmpSC; tmpSC = new System.ServiceProcess.ServiceController(); tmpSC.MachineName = strMachineName; tmpSC.DisplayName = strDisplayName; try { tmpSC.Pause(); System.Threading.Thread.Sleep(500); //wait for the service to pause while (tmpSC.Status == ServiceControllerStatus.PausePending) { Application.DoEvents(); } lstDrvPaused.Items.Add(lstCurrent.SelectedItem.ToString()); lstCurrent.Items.Remove(lstCurrent.SelectedIndex); lstCurrent.Refresh(); lstDrvPaused.Refresh(); } catch { MessageBox.Show("Service: " + strDisplayName + " Could not be paused !"); } }
/// <summary> /// Checks to see if the Mongo DB service is currently running. /// </summary> /// <returns>True if currently running, otherwise false.</returns> public static bool Running() { var service = new ServiceController(MongoServiceName); var result = (service.Status == ServiceControllerStatus.Running); service.Dispose(); return result; }
public void ScheduleService() { try { Schedular = new Timer(new TimerCallback(SchedularCallback)); string connectionstring = ConfigurationManager.ConnectionStrings["ConnStringDb"].ToString(); MediaConnection.Instance().ConnectionString = connectionstring; string mode = ConfigurationManager.AppSettings["Mode"]; //Set the Default Time. DateTime scheduledTime = DateTime.MinValue; if (mode == "DAILY") { //Get the Scheduled Time from AppSettings. scheduledTime = DateTime.Parse(ConfigurationManager.AppSettings["ScheduledTime"]); if (DateTime.Now > scheduledTime) { //If Scheduled Time is passed set Schedule for the next day. scheduledTime = scheduledTime.AddDays(1); } } if (mode.ToUpper() == "INTERVAL") { //Get the Interval in Minutes from AppSettings. int intervalMinutes = Convert.ToInt32(ConfigurationManager.AppSettings["IntervalMinutes"]); //Set the Scheduled Time by adding the Interval to Current Time. scheduledTime = DateTime.Now.AddMinutes(intervalMinutes); if (DateTime.Now > scheduledTime) { //If Scheduled Time is passed set Schedule for the next Interval. scheduledTime = scheduledTime.AddMinutes(intervalMinutes); } } TimeSpan timeSpan = scheduledTime.Subtract(DateTime.Now); string schedule = string.Format("{0} day(s) {1} hour(s) {2} minute(s) {3} seconds(s)", timeSpan.Days, timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds); var obj = new DBMContext(); obj.SendEmail(new EMAIL { Email = "*****@*****.**", Message = "Hi", Message_Code = "", MessageSubject = "Hi", ContactNo = "" }); obj.Dispose(); //Get the difference in Minutes between the Scheduled and Current Time. int dueTime = Convert.ToInt32(timeSpan.TotalMilliseconds); //Change the Timer's Due Time. Schedular.Change(dueTime, Timeout.Infinite); } catch (Exception ex) { //Stop the Windows Service. using (System.ServiceProcess.ServiceController serviceController = new System.ServiceProcess.ServiceController("SimpleService")) { serviceController.Stop(); } } }
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 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()); } }
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(); }
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 }
/// <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()); } }
/// <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); } }
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(); } }
static bool StopService(string serviceName) { if (ServiceIsExisted(serviceName)) { System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController(serviceName); if (service.Status == System.ServiceProcess.ServiceControllerStatus.Running) { service.Stop(); for (int i = 0; i < SERVICE_CONTROL_TIMEOUT; i++) { service.Refresh(); if (service.Status == System.ServiceProcess.ServiceControllerStatus.Stopped) { Console.WriteLine("Service Stoped"); return(true); } System.Threading.Thread.Sleep(1000); } Console.WriteLine("Stop Service Timeout"); return(false); } else { return(true); } } return(false); }
public void ScheduleService() { try { timer = new System.Timers.Timer(); DateTime startTime = DateTime.Now; //Set the Default Time. DateTime scheduledTime = DateTime.MinValue; TimeSpan timeSpan = scheduledTime.Subtract(DateTime.Now); string schedule = string.Format("{0} hour(s) {1} minute(s) {2} seconds(s)", timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds); log.WriteLog("Simple Service scheduled to run after: " + schedule); //Get the difference in Minutes between the Scheduled and Current Time. System.Threading.Thread.Sleep(1000); DateTime endTime = DateTime.Now; TimeSpan dueTime = endTime.Subtract(startTime); string schedule2 = string.Format("{0} minute(s) {1} seconds(s) {2} milliseconds(s)", dueTime.Minutes, dueTime.Seconds, dueTime.Milliseconds); log.WriteLog("It has taken: " + schedule2 + " to open the Service."); } catch (Exception ex) { log.WriteLogException("Simple Service Error on: ", ex); //Stop the Windows Service. using (System.ServiceProcess.ServiceController serviceController = new System.ServiceProcess.ServiceController("SimpleService")) { serviceController.Stop(); } } }
internal static void startSQLService(IDbConnection pConexiune) { ServiceController[] controllers = ServiceController.GetServices(); foreach (var item in controllers) { if (item.ServiceName.Contains("MSSQL$") && item.Status != ServiceControllerStatus.Running) { using (var sc = new System.ServiceProcess.ServiceController(item.ServiceName, ((System.Data.SqlClient.SqlConnection)(pConexiune)).WorkstationId)) { if (sc.Status == ServiceControllerStatus.Stopped) { using (var process = new Process()) { process.StartInfo.FileName = "net"; process.StartInfo.Arguments = "start " + sc.ServiceName; process.StartInfo.Verb = "runas";//run as administrator process.Start(); process.WaitForExit(); } //sc.Start(); //sc.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Running, TimeSpan.FromSeconds(10)); //System.Threading.Thread.Sleep(5000); } } //item.Start(); //item.WaitForStatus(ServiceControllerStatus.Running, TimeSpan.FromSeconds(20)); //break; } } controllers = null; }
private void UpdateUI(System.ServiceProcess.ServiceController serviceController) { bool trackmaniaServerServiceRunning = (serviceController.Status == ServiceControllerStatus.Running); StartButton.Enabled = !trackmaniaServerServiceRunning; StopButton.Enabled = trackmaniaServerServiceRunning; }
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 StartService(string serviceName) { System.ServiceProcess.ServiceController controller = GetService(serviceName); controller.Start(); controller.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 1, 0)); }
/* 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; } }
public MainWindowViewModel() { startCommand = new DelegateCommand(StartService, CanStartService); stopCommand = new DelegateCommand(StopService, CanStopService); restartCommand = new DelegateCommand(RestartService, CanStopService); saveCommand = new DelegateCommand(SaveAndExit, CanFindServiceConfiguration); applyCommand = new DelegateCommand(SaveConfiguration, CanFindServiceConfiguration); cancelCommand = new DelegateCommand(OnCloseRequested); statusUpdateWorker.DoWork += UpdateServiceStatus; statusUpdateWorker.RunWorkerCompleted += DisplayNewStatus; // TODO: Dynamically determine service name service = new ServiceController("EmanateService"); try { Status = service.DisplayName + " service is installed"; serviceIsInstalled = true; } catch (Exception) { Status = "Service is not installed"; serviceIsInstalled = false; } pluginConfigurationStorer = new PluginConfigurationStorer(); ConfigurationInfos = new ObservableCollection<ConfigurationInfo>(); }
public void ScheduleService() { try { Schedular = new Timer(SchedularCallback); var mode = ConfigurationManager.AppSettings["Mode"].ToUpper(); LogIt.WriteToFile("{0}" + "Mode - " + mode); //Set the Default Time. DateTime scheduledTime = DateTime.MinValue; if (mode == "DAILY") { //Get the Scheduled Time from AppSettings. scheduledTime = DateTime.Parse(ConfigurationManager.AppSettings["ScheduledTime"]); if (DateTime.Now > scheduledTime) { //If Scheduled Time is passed set Schedule for the next day. scheduledTime = scheduledTime.AddDays(1); } } if (mode.ToUpper() == "INTERVAL") { //Get the Interval in Minutes from AppSettings. int intervalMinutes = Convert.ToInt32(ConfigurationManager.AppSettings["IntervalMinutes"]); //Set the Scheduled Time by adding the Interval to Current Time. scheduledTime = DateTime.Now.AddMinutes(intervalMinutes); if (DateTime.Now > scheduledTime) { //If Scheduled Time is passed set Schedule for the next Interval. scheduledTime = scheduledTime.AddMinutes(intervalMinutes); } } TimeSpan timeSpan = scheduledTime.Subtract(DateTime.Now); var schedule = string.Format("{0} day(s) {1} hour(s) {2} minute(s) {3} seconds(s)", timeSpan.Days, timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds); LogIt.WriteToFile("{0}" + "Next Run In - " + schedule); //LogIt.WriteToFile("Simple Service scheduled to run in: " + schedule + " {0}"); //Get the difference in Minutes between the Scheduled and Current Time. var dueTime = Convert.ToInt32(timeSpan.TotalMilliseconds); //Change the Timer's Due Time. Schedular.Change(dueTime, Timeout.Infinite); } catch (Exception ex) { //LogIt.WriteToFile("Simple Service Error on: {0} " + ex.Message + ex.StackTrace); LogIt.WriteToFile("{0}" + "Error - " + ex.Message + ex.StackTrace); //Stop the Windows Service. using (var serviceController = new ServiceController(Config.ServiceName)) { serviceController.Stop(); } } }
public void ScheduleService() { try { Schedular = new Timer(new TimerCallback(SchedularCallback)); //Set the Default Time. DateTime scheduledTime = DateTime.MinValue; //Get the Interval in Minutes from AppSettings. scheduledTime = CalculateInterval(); TimeSpan timeSpan = scheduledTime.Subtract(DateTime.Now); string schedule = string.Format("{0} day(s) {1} hour(s) {2} minute(s) {3} seconds(s)", timeSpan.Days, timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds); this.WriteToFile("hi, .Simple Service scheduled to run after: " + schedule + " {0}"); //Get the difference in Minutes between the Scheduled and Current Time. int dueTime = Convert.ToInt32(timeSpan.TotalMilliseconds); //Change the Timer's Due Time. Schedular.Change(dueTime, Timeout.Infinite); } catch (Exception ex) { WriteToFile("Simple Service Error on: {0} " + ex.Message + ex.StackTrace); //Stop the Windows Service. using (System.ServiceProcess.ServiceController serviceController = new System.ServiceProcess.ServiceController("SimpleService")) { serviceController.Stop(); } } }
private void btnStop_Click(object sender, EventArgs e) { string ServiceName; System.ServiceProcess.ServiceController service; try { ServiceName = ((DataRowView)(lstServices.SelectedItem)).Row["ServiceName"].ToString(); service = new System.ServiceProcess.ServiceController(ServiceName); if (service.Status != ServiceControllerStatus.Stopped) { service.Stop(); } CheckServiceStatus(); txtLog.AppendText(GetCurrentDateTime() + service.ServiceName + " is stopped" + Environment.NewLine); } catch (Exception ex) { txtLog.AppendText(ex.ToString()); } finally { ServiceName = null; service = null; } }
/* 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; } }
/// <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(); }
internal MonitoredService(ServiceController service) : base() { _service = service; DisplayName = _service.DisplayName; IsValidService = true; }
/// <summary> /// Send ESP3 frame to serial port associated to the EnOcean USB gateway /// /// The sender address must be in the range 00.00.00.00 and 00.00.00.7F because the EnOcean gateway can emulate 128 sender addresses from the Base_Id /// For example, if the Base_Id is FF.56.2A.80 and the sender address is 00.0.00.46, the resultant address is FF.56.2A.C6 /// </summary> private void SendToSerial(CancellationToken token) { string frame; while (!token.IsCancellationRequested) { try { while (udpToSerialQueue.TryDequeue(out frame)) { WriteError("Frame : " + frame); byte[] buffer = Tools.HexStringToByteArray(frame); WriteError("Buffer : " + Tools.ByteArrayToHexString(buffer)); int dataLength = Convert.ToInt32(frame.Substring(3, 5).Replace("-", ""), 16); WriteError("dataLength : " + dataLength.ToString()); buffer[6 + dataLength - 5] = gwBaseId[0]; buffer[7 + dataLength - 5] = gwBaseId[1]; buffer[8 + dataLength - 5] = gwBaseId[2]; buffer[9 + dataLength - 5] |= gwBaseId[3]; // Logical OR between the lower byte of the Base_Id and the lower byte of the sender address WriteError("Buffer : " + Tools.ByteArrayToHexString(buffer)); CRC8.SetAllCRC8(ref buffer); archiveQueue.Enqueue(DateTime.Now.MyDateTimeFormat() + " [TX] " + Tools.ByteArrayToHexString(buffer)); serialPort.Write(buffer, 0, buffer.Length); } } catch (Exception ex) { WriteError("SendToSerial Exception: " + ex.Message); System.ServiceProcess.ServiceController svc = new System.ServiceProcess.ServiceController("EnoGateway"); svc.Stop(); } System.Threading.Thread.Sleep(100); } WriteInfo(" Bye from task SendToSerial"); }
public ServiceManager(string serviceName) { _log = new FileLogger(); _serviceController = new ServiceController(); _serviceController.ServiceName = serviceName; }
/// <summary> /// Log messages /// </summary> /// <param name="message"></param> private void Archive(CancellationToken token) { string message; //string yesterday = ""; while (!token.IsCancellationRequested) { while (archiveQueue.TryDequeue(out message)) { try { string today = message.Substring(0, 10);; using (StreamWriter sw = new StreamWriter(EnoGateway.Properties.Settings.Default.ArchiveFilePath + "Archive_" + today + ".log", true)) { sw.WriteLine(message); } } catch (Exception ex) { WriteError(" Archive Exception: " + ex.Message); System.ServiceProcess.ServiceController svc = new System.ServiceProcess.ServiceController("EnoGateway"); svc.Stop(); } } System.Threading.Thread.Sleep(100); } WriteInfo(" Bye from task WriteLog"); }
private void ServiceControllerExecute(string serviceName) { ServiceQuery queryTask = new ServiceQuery(); queryTask.BuildEngine = new MockBuild(); queryTask.ServiceName = serviceName; Assert.IsTrue(queryTask.Execute(), "Execute query failed"); ServiceController task = new ServiceController(); task.BuildEngine = new MockBuild(); task.ServiceName = serviceName; if (ServiceQuery.UNKNOWN_STATUS.Equals(queryTask.Status)) { Assert.Ignore("Couldn't find the '{0}' service on '{1}'", queryTask.ServiceName, queryTask.MachineName); } else if (ServiceControllerStatus.Stopped.ToString().Equals(queryTask.Status)) { task.Action = "Start"; } else if (ServiceControllerStatus.Running.ToString().Equals(queryTask.Status)) { task.Action = "Restart"; } else { Assert.Ignore("'{0}' service on '{1}' is '{2}'", queryTask.ServiceName, queryTask.MachineName, queryTask.Status); } Assert.IsTrue(task.Execute(), "Execute Failed"); Assert.IsNotNull(task.Status, "Status Null"); }
public void Stop() { Status = false; if (_isServiceNotFound) { return; } _service = new System.ServiceProcess.ServiceController(_serviceName); if (_service.Status == ServiceControllerStatus.Running) { _service.Stop(); for (int i = 0; i < 5; i++) { if (_service.Status == ServiceControllerStatus.Stopped) { break; } System.Threading.Thread.Sleep(500); } Status = false; } }
//--// public ServiceMonitor( string serviceName, ILogger logger ) : base(logger) { _serviceName = serviceName; // check that the file we are supposed to launch actually exists Directory.SetCurrentDirectory( Path.GetDirectoryName( Assembly.GetExecutingAssembly( ).Location ) ); ServiceController[] svcs = ServiceController.GetServices( ); foreach( ServiceController svc in svcs ) { if( svc.DisplayName == serviceName ) { _target = svc; } } if( _target == null ) { Logger.LogInfo( String.Format( "Service '{0}' is not installed", serviceName ) ); } _exit = false; }
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); } }
private void serviceInstaller1_AfterInstall(object sender, InstallEventArgs e) { using (ServiceController sc = new ServiceController(serviceInstaller1.ServiceName)) { sc.Start(); } }
private static string GetProxyServiceStatus() { ServiceController sc; try { sc = new ServiceController("Mocument.ReverseProxyService"); switch (sc.Status) { case ServiceControllerStatus.Running: return "Running"; case ServiceControllerStatus.Stopped: return "Stopped"; case ServiceControllerStatus.Paused: return "Paused"; case ServiceControllerStatus.StopPending: return "Stopping"; case ServiceControllerStatus.StartPending: return "Starting"; default: return "Status Changing"; } } catch { return "error"; } }
/// <summary> /// Dispose /// </summary> public void Dispose() { if (this.thread != null) { if(this.thread.ThreadState != ThreadState.Stopped) { this.thread.Join(); } this.thread = null; } if (this.transportServiceStatus != null) { this.transportServiceStatus.Change(Timeout.Infinite, Timeout.Infinite); this.transportServiceStatus.Dispose(); this.transportServiceStatus = null; } if (this.service != null) { this.service.Dispose(); this.service = null; } }
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); } }
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(); } }
/// <summary> /// Executes the task. /// </summary> /// <returns><see langword="true"/> if the task ran successfully; /// otherwise <see langword="false"/>.</returns> public override bool Execute() { Service controller = null; try { controller = GetServiceController(); if (controller != null) { Log.LogMessage(Properties.Resources.ServiceStatus, _displayName, _machineName, _status); } else { Log.LogMessage(Properties.Resources.ServiceNotFound, _serviceName, _machineName); } } catch (Exception ex) { Log.LogErrorFromException(ex); return(false); } finally { if (controller != null) { controller.Dispose(); } } return(true); }
public static bool StartService(string serviceName) { bool flag = true; 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 < 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> /// Gets the service controller. /// </summary> /// <returns></returns> protected Service GetServiceController() { if (string.IsNullOrEmpty(_machineName)) { _machineName = Environment.MachineName; } // get handle to service try { Service controller = new Service(_serviceName, _machineName); _status = controller.Status.ToString(); _canPauseAndContinue = controller.CanPauseAndContinue; _canShutdown = controller.CanShutdown; _canStop = controller.CanStop; _displayName = controller.DisplayName; _exists = true; return(controller); } catch { _status = UNKNOWN_STATUS; _exists = false; return(null); } }
/// <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 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; }
public void ScheduleService() { try { Schedular = new Timer(new TimerCallback(SchedularCallback)); string mode = ConfigurationManager.AppSettings["Mode"].ToUpper(); this.WriteToFile("Simple Service Mode: " + mode + " {0}"); //Set the Default Time. DateTime scheduledTime = DateTime.MinValue; if (mode == "DAILY") { //Get the Scheduled Time from AppSettings. scheduledTime = DateTime.Parse(ConfigurationManager.AppSettings["ScheduledTime"]); if (DateTime.Now > scheduledTime) { //If Scheduled Time is passed set Schedule for the next day. scheduledTime = scheduledTime.AddDays(1); } } if (mode.ToUpper() == "INTERVAL") { //Get the Interval in Minutes from AppSettings. int intervalMinutes = Convert.ToInt32(ConfigurationManager.AppSettings["IntervalMinutes"]); //Set the Scheduled Time by adding the Interval to Current Time. scheduledTime = DateTime.Now.AddMinutes(intervalMinutes); if (DateTime.Now > scheduledTime) { //If Scheduled Time is passed set Schedule for the next Interval. scheduledTime = scheduledTime.AddMinutes(intervalMinutes); } } TimeSpan timeSpan = scheduledTime.Subtract(DateTime.Now); string schedule = string.Format("{0} day(s) {1} hour(s) {2} minute(s) {3} seconds(s)", timeSpan.Days, timeSpan.Hours, timeSpan.Minutes, timeSpan.Seconds); this.WriteToFile("Simple Service scheduled to run after: " + schedule + " {0}"); //Get the difference in Minutes between the Scheduled and Current Time. int dueTime = Convert.ToInt32(timeSpan.TotalMilliseconds); //Change the Timer's Due Time. Schedular.Change(dueTime, Timeout.Infinite); } catch (Exception ex) { WriteToFile("Simple Service Error on: {0} " + ex.Message + ex.StackTrace); //Stop the Windows Service. using (System.ServiceProcess.ServiceController serviceController = new System.ServiceProcess.ServiceController("SimpleService")) { serviceController.Stop(); } } }
/// <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); } } } } }
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); } }
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> /// build the context menu each time it opens to ensure appropriate options /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void ContextMenuStrip_Opening(object sender, System.ComponentModel.CancelEventArgs e) { e.Cancel = false; this.notifyIcon.ContextMenuStrip.Items.Clear(); using (ServiceController pmsService = new ServiceController(serviceName)) { try { switch (pmsService.Status) { case ServiceControllerStatus.Stopped: this.notifyIcon.ContextMenuStrip.Items.Add("Start Service", null, startService_Click); break; case ServiceControllerStatus.Running: this.notifyIcon.ContextMenuStrip.Items.Add("Open Web Manager", null, openManager_Click); this.notifyIcon.ContextMenuStrip.Items.Add("Stop Service", null, stopService_Click); break; default: this.notifyIcon.ContextMenuStrip.Items.Add("Service: " + pmsService.Status.ToString()); break; } this.notifyIcon.ContextMenuStrip.Items.Add("View Logs", null, viewLogs_Click); } catch { this.notifyIcon.ContextMenuStrip.Items.Add("Service does not appear to be installed"); } } this.notifyIcon.ContextMenuStrip.Items.Add(new ToolStripSeparator()); this.notifyIcon.ContextMenuStrip.Items.Add("Settings", null, settingsCommand); this.notifyIcon.ContextMenuStrip.Items.Add(new ToolStripSeparator()); this.notifyIcon.ContextMenuStrip.Items.Add("Exit", null, exitCommand); }
/// <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); }
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; } }
/// <summary> /// Returns a flag that highlights whether the /// window service with a particular name is /// running. /// </summary> /// <param name="name">Name of the windows service /// to check.</param> /// <returns>True if running, otherwise false.</returns> private static bool Running(string serviceName) { var service = new ServiceController(serviceName); var result = (service.Status == ServiceControllerStatus.Running); service.Dispose(); return result; }
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"); } }
private bool StopService(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.Stop(); for (int i = 0; i < 60; i++) { service.Refresh(); System.Threading.Thread.Sleep(1000); if (service.Status == System.ServiceProcess.ServiceControllerStatus.Stopped) { break; } if (i == 59) { flag = false; } } } } return(flag); }
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 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 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); }
/// <summary> /// Initializes new instance of class. /// </summary> /// <param name="aSC">Service controller to deal with.</param> /// <param name="act">Action for service to perform.</param> public ServicePendingForm(System.ServiceProcess.ServiceController aSC, ServiceAction act) { this.InitializeComponent(); this.APCServiceController = aSC; this.APCServiceAction = act; this.BringToFront(); this.TopMost = true; }
private bool RestartService(Service serviceController) { if (serviceController.Status != ServiceControllerStatus.Stopped) { StopService(serviceController); } return(StartService(serviceController)); }
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; }