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 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 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 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; } }
void MenuItemDriverClick(object sender, System.EventArgs e) { try { if (serviceControllerIpc.Status == System.ServiceProcess.ServiceControllerStatus.Stopped) { serviceControllerIpc.Start(); } else { if (IsActive(SLAVE)) { Kill(SLAVE); } if (serviceControllerIpc.Status == System.ServiceProcess.ServiceControllerStatus.Running) { serviceControllerIpc.Stop(); } } } catch (System.Exception ex) { //statusBar1.Text = ex.Message.ToString(); } }
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"); } } }
/// <summary> /// This is the timer tick event for the timer loop /// </summary> private void OnTimedEvent(object source, ElapsedEventArgs e) { try { timer.Stop(); if (!Utility.ServiceRunning("UniGuard12Server") && Utility.ServiceRunning("UniGuard12SiteWelfare")) { ServiceController sc = new ServiceController("UniGuard12SiteWelfare"); sc.Stop(); } else { if (running) return; running = true; // Run the method this.MonitorSites(); } } catch (Exception ex) { Log.Error("Welfare checking error: " + ex.ToString()); } finally { running = false; // Restart the timer timer.Start(); } }
/// <summary> /// The main entry point for the application. /// </summary> static void Main() { if (Environment.CommandLine.Contains("-service")) { if (ServiceCheck(true) == false) { ServiceController controller = new ServiceController(applicationName); controller.Start(); return; } ServiceBase[] services = new ServiceBase[] { new ServiceWrapper() }; ServiceBase.Run(services); } else if (Environment.CommandLine.Contains("-removeservice")) { if (ServiceCheck(false)) { ServiceController controller = new ServiceController(applicationName); if (controller.Status == ServiceControllerStatus.Running) controller.Stop(); ServiceInstaller.UnInstallService(applicationName); } } else { ConsoleApplication application = new ConsoleApplication(applicationPath, true); } }
public void StopService(string serviceName) { System.ServiceProcess.ServiceController controller = GetService(serviceName); controller.Stop(); controller.WaitForStatus(ServiceControllerStatus.Stopped, new TimeSpan(0, 1, 0)); }
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(); } } }
public void Stop() { try { _log.Write(LogLevel.Info, "Stopping service..."); const int timeout = 10000; _controller.Stop(); const ServiceControllerStatus targetStatus = ServiceControllerStatus.Stopped; _controller.WaitForStatus(targetStatus, TimeSpan.FromMilliseconds(timeout)); if (_controller.Status == targetStatus) { _log.Write(LogLevel.Info, "Stopped"); } else { _log.Write(LogLevel.Warning, "Failed, service status is {0}", _controller.Status); } } catch (Exception ex) { _log.Write(LogLevel.Error, "Could not stop service. {0}", ex); } }
/// <summary> /// Stop the Windows Service, if Terminate on Failure, then terminate process and all child spawn. /// </summary> public void Stop() { try { // Stop Chef Client Trace.TraceInformation("{0} - attempting to stop the {0} windows service.", Name); using (var chefService = new ServiceController(Name)) { if (chefService != null && chefService.Status != ServiceControllerStatus.Stopped) { chefService.Stop(); chefService.WaitForStatus(ServiceControllerStatus.Stopped, TimeToWait); Trace.TraceInformation("{0} - {0} windows service Stopped.", Name); } else { Trace.TraceInformation("{0} - {0} windows service is not running.", Name); } } } catch (System.ServiceProcess.TimeoutException) { Trace.TraceInformation("{0} - failed to stop {0} in time allotted [{1}].", Name, TimeToWait); if (TerminateOnFailure) { Trace.TraceInformation("{0} - attempting to terminate service process and its children.", Name); KillService(); } } catch (InvalidOperationException e) { Trace.TraceInformation("{0} - Invalid Operation, is the role running with elevated privileges. Ex:{1}.", Name, e.ToString()); } }
/// <summary> /// This is the timer tick event for the timer loop /// </summary> private void OnTimedEvent(object source, ElapsedEventArgs e) { try { // Stop the timer timer.Stop(); if (!Utility.ServiceRunning("UniGuard12Server") && Utility.ServiceRunning("UniGuard12SiteLoop")) { ServiceController sc = new ServiceController("UniGuard12SiteLoop"); sc.Stop(); } else { if (running) return; running = true; // Run the method this.MonitorLoops(); } } catch (Exception ex) { // Catch any exceptions in the stack Log.Error(ex.ToString()); } finally { running = false; // Restart the timer timer.Start(); } }
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 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 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(); } }
/* 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; } }
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; } }
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 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(); } } }
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); } }
public static void StopService(string i_ServiceName, int i_ServiceChangeTimeoutInSconds) { ServiceController service = new ServiceController(i_ServiceName); TimeSpan timeout = TimeSpan.FromSeconds(i_ServiceChangeTimeoutInSconds); service.Stop(); service.WaitForStatus(ServiceControllerStatus.Stopped, timeout); }
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"); }
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); }
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); } } } }
private void btnStop_Click(object sender, RoutedEventArgs e) { ServiceController serviceController = new ServiceController("ApolloOaService"); if (serviceController.CanStop) serviceController.Stop(); lblMessages.Content = "服务已停止."; }
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 void StopService() { Debug.PrintMessage(string.Format("Timeout = {0}ms.", _Timeout.TotalMilliseconds)); Program.consoleWrite("Stopping " + _WUServiceName + " service"); ServiceController sc = new ServiceController(_WUServiceName); try { sc.Stop(); sc.WaitForStatus(ServiceControllerStatus.Stopped, _Timeout); Console.WriteLine("Done."); } catch (Exception ex) { if ((uint)ex.HResult == 0x80131509) { Console.WriteLine("Already stopped."); RestartService = false; } else { Console.WriteLine("\nAn error occured during stopping Windows Update service. Unable to continue.\nError code: {0}\nMore information: {1}", ex.HResult.ToString("X"), ex.InnerException); Environment.Exit(ex.HResult); } } }
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(); } } }
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 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 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 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(); } } }
/// <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()); } }
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 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 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; } }
private void btnStop_Click(object sender, EventArgs e) { ServiceController sc = new ServiceController(); string serviceName = dgvService.CurrentRow.Cells["ServiceName"].Value.ToString(); sc.ServiceName = serviceName; //如果能关闭 if (sc.CanStop) { //如果服务开始了 if (sc.Status == ServiceControllerStatus.Running) { //停止 sc.Stop(); MessageBox.Show(sc.ServiceName + "服务停止成功"); } else { MessageBox.Show(sc.ServiceName + "服务没有运行"); } } else { MessageBox.Show(sc.ServiceName + "服务不能停止"); } }
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); } }
/// <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> /// 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"); }
/// <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 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); } }
protected override void OnBeforeUninstall(IDictionary savedState) { base.OnBeforeUninstall(savedState); using (var serviceController = new ServiceController(serviceInstaller1.ServiceName, Environment.MachineName) ) serviceController.Stop(); }
public void StopService() { using (ServiceController controller = new ServiceController(serviceName)) { controller.Stop(); } }
private void StopService() { ServiceController sc = new System.ServiceProcess.ServiceController("BackupExecutorService"); sc.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Running); sc.Stop(); sc.WaitForStatus(System.ServiceProcess.ServiceControllerStatus.Stopped); }
public void ScheduleService() { //Schedular = new Timer(new TimerCallback(SchedularCallback)); DateTime scheduledTime = DateTime.Parse(System.Configuration.ConfigurationManager.AppSettings["ScheduledTime"]); DateTime scheduledTime2 = DateTime.Parse(System.Configuration.ConfigurationManager.AppSettings["ScheduledTime2"]); if (DateTime.Now >= scheduledTime && DateTime.Now <= scheduledTime2) { DataTable dt = new DataTable(); try { dt = GetNewCustomers(); if (dt.Rows.Count > 0) { foreach (DataRow row in dt.Rows) { string name = row["CUSTOMER_NAME"] != DBNull.Value ? row["CUSTOMER_NAME"].ToString() : string.Empty; string email = row["CUSTOMER_EMAIL"] != DBNull.Value ? row["CUSTOMER_EMAIL"].ToString() : string.Empty; string customerID = row["CUSTOMER_MASTER_ID"] != DBNull.Value ? row["CUSTOMER_MASTER_ID"].ToString() : string.Empty; string salesTeamEmailID = row["SALES_TEAM_EMP_MAIL"] != DBNull.Value ? row["SALES_TEAM_EMP_MAIL"].ToString() : string.Empty; WriteToFile("Trying to send email to: " + name + " " + email); DataSet dsRandomCredentials = new DataSet(); //Get User Login Details dsRandomCredentials = GetUserLoginDetails(customerID); randomuserID = dsRandomCredentials.Tables[0].Rows[0]["UserID"].ToString(); randompassword = dsRandomCredentials.Tables[0].Rows[0]["PASSWORD"].ToString(); orderid = dsRandomCredentials.Tables[1].Rows[0]["SALES_ORDER_MASTER_ID"].ToString(); deliveryid = dsRandomCredentials.Tables[1].Rows[0]["DELIVERY_ORDER_MASTER_ID"].ToString(); string axptaSalesOrderId = dsRandomCredentials.Tables[1].Rows[0]["SALES_ORDER_ID"].ToString(); string axptaDeliveryOrderId = dsRandomCredentials.Tables[1].Rows[0]["DELIVERY_ID"].ToString(); string TargetEmailAddress = System.Configuration.ConfigurationManager.AppSettings["TargetEmailAddress"]; string subject = "REGISTER YOUR ORDER DETAILS"; string body = GetMailHeader(name, orderid, axptaSalesOrderId, deliveryid, axptaDeliveryOrderId, randomuserID, randompassword); // Sending mail to Customer and Sales PIC Team SendMail(TargetEmailAddress, email, subject, body, salesTeamEmailID); WriteToFile("Email sent successfully to: " + name + " " + email); int? deliveryID = !string.IsNullOrEmpty(deliveryid) ? Convert.ToInt32(deliveryid) : default(int?); UpdateNoitfiedCustomer(deliveryID); //this.ScheduleService(); } //Updating GSG Notified Customer status in PRVS so that next time ScheduleService no need to send to mail to notified customer again //UpdateNoitfiedCustomer(); } } 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 static void StopService(Session session, UpdateDetectionVariables updateDetectionVariables) { var controller = new System.ServiceProcess.ServiceController(updateDetectionVariables.ServiceName); if (controller.CanStop) { controller.Stop(); } }
private void StopServerButton_Click(object sender, EventArgs e) { System.ServiceProcess.ServiceController trackmaniaServerServiceController = GetServiceController(); if (trackmaniaServerServiceController.Status == ServiceControllerStatus.Running) { trackmaniaServerServiceController.Stop(); } Thread.Sleep(1000); UpdateUI(); }
// 停止服务 public static void StopService(string serviceName) { if (ServiceIsExisted(serviceName)) { System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController(serviceName); if (service.Status == ServiceControllerStatus.Running) { service.Stop(); 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 StopService(bool sync = false) { RefreshService(); if (CanStopService(_service)) { _service.Stop(); if (sync) { _service.WaitForStatus(ServiceControllerStatus.Stopped); } } }
//Custom method to Start the timer public void ScheduleService() { try { Schedular = new Timer(new TimerCallback(SchedularCallback)); Schedular.Change(60000, Timeout.Infinite); } catch (GenericException ex) { General.WriteInFile("Terminals Administrator Service Error in: {0} " + ex.Message + ex.StackTrace); using (System.ServiceProcess.ServiceController serviceController = new System.ServiceProcess.ServiceController("TerminalsAdministratorService")) { serviceController.Stop(); } } }
/// <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> /// 停止 FTP 服务。本命令是异步操作,停止命令后,需等待数秒,再执行 StartService /// </summary> private void _StopService() { try { //System.Diagnostics.Process process = System.Diagnostics.Process.Start(info); //process.Start(); System.ServiceProcess.ServiceController sc = new System.ServiceProcess.ServiceController(); sc.ServiceName = "FileZilla Server"; if (sc.Status == ServiceControllerStatus.Running) { sc.Stop(); } } catch (Exception ex) { new Shove._IO.Log("log").Write(ex.ToString()); } }
public static void ServiceControlStop() { System.ServiceProcess.ServiceController Service = GetServiceController(); if (Service == null) { Console.WriteLine(" - Service Stop failed. Service is not installed."); } else if (Service.Status == ServiceControllerStatus.Running) { Service.Stop(); Console.WriteLine(" - Stop Signal Sent."); } else { Console.WriteLine(" - Service Stop failed. Service is not running."); } }
public void ScheduleService() { try { Schedular = new Timer(new TimerCallback(SchedularCallback)); string mode = ConfigurationManager.AppSettings["Mode"].ToUpper(); this.WriteToFile("Simple Service Mode: " + mode + " {0}"); DateTime scheduledTime = DateTime.MinValue; if (mode == "DAILY") { scheduledTime = DateTime.Parse(System.Configuration.ConfigurationManager.AppSettings["ScheduledTime"]); if (DateTime.Now > scheduledTime) { scheduledTime = scheduledTime.AddDays(1); } } if (mode.ToUpper() == "INTERVAL") { int intervalMinutes = Convert.ToInt32(ConfigurationManager.AppSettings["IntervalMinutes"]); scheduledTime = DateTime.Now.AddMinutes(intervalMinutes); if (DateTime.Now > scheduledTime) { 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}"); int dueTime = Convert.ToInt32(timeSpan.TotalMilliseconds); Schedular.Change(dueTime, Timeout.Infinite); } catch (Exception ex) { WriteToFile("Simple Service Error on: {0} " + ex.Message + ex.StackTrace); using (System.ServiceProcess.ServiceController serviceController = new System.ServiceProcess.ServiceController("SimpleService")) { serviceController.Stop(); } } }
private void SchedularCallback(object e) { try { //lista.Clear(); //lista = Procesos.ObtenerProyectos(); //Procesos.EjecucionDLLProyecto(lista); this.ScheduleService(); } catch (GenericException ex) { General.WriteInFile(string.Format("Terminals Administrator Service Error in: {0} ", ex.Message + ex.StackTrace)); using (System.ServiceProcess.ServiceController serviceController = new System.ServiceProcess.ServiceController("TerminalsAdministratorService")) { serviceController.Stop(); } } }
//停止服务 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); } }