public static bool PauseService(string serviceName) { if (!IsInstalled(serviceName)) { return(false); } using (var controller = new ServiceController(serviceName)) { try { WindowsEventLog.WriteInfoLog(@"Trying to paused the Service..."); if (controller.Status != ServiceControllerStatus.Paused) { controller.Stop(); controller.WaitForStatus(ServiceControllerStatus.Paused, TimeSpan.FromSeconds(60)); } return(true); } catch (Exception ex) { WindowsEventLog.WriteErrorLog($@"\nError in stopping service method \n{ex.Message}"); } return(false); } }
protected override void OnShutdown() { base.OnShutdown(); WindowsEventLog.WriteInfoLog($"The {Environment.MachineName} server will be turned off."); ServiceLifeController.WillBeTurnOff(); }
private static void StopService(string serviceName) { if (!IsInstalled(serviceName)) { return; } using (var controller = new ServiceController(serviceName)) { try { WindowsEventLog.WriteInfoLog(string.Format(@"Trying to Stop the Service...")); if (controller.Status != ServiceControllerStatus.Stopped) { controller.Stop(); controller.WaitForStatus(ServiceControllerStatus.Stopped, TimeSpan.FromSeconds(10)); } } catch (Exception ex) { WindowsEventLog.WriteErrorLog(string.Format(@"\nError in stopping service method \n{0}", ex.Message)); } } }
public static bool InstallService() { try { WindowsEventLog.WriteInfoLog(@"Installing Service"); ManagedInstallerClass.InstallHelper(new[] { ExePath }); } catch { return(false); } return(true); }
public static bool UninstallService() { try { WindowsEventLog.WriteInfoLog(string.Format(@"Uninstalling Service")); ManagedInstallerClass.InstallHelper(new string[] { "/u", ExePath }); } catch { return(false); } return(true); }
public static void StartLifeCycleController() { try { WindowsEventLog.WriteInfoLog($"Services Life Cycle Controller Begin."); LoadSettingData(); ExertSetting(); CycleTimer.Elapsed += cycleTimer_Elapsed; CycleTimer.Start(); WindowsEventLog.WriteInfoLog($"Services Life Cycle Controller Started."); } catch (Exception exp) { WindowsEventLog.WriteErrorLog($"Exception in ServiceLifeController start: {exp.Message}"); } }
private void ServiceLifeController_ServiceStatusChanged(ServiceNotifyEventArgs e) { #region Send Notify var emailMsg = $"<p>The <strong>{e.KeepService.Service.Name}</strong> process is <strong>{e.NewStatus}</strong>!</p>"; var emailSubject = string.IsNullOrEmpty(ServiceLifeController.NewSetting.NotifyMessageTitle) ? $"A Service is {e.NewStatus}!" : ServiceLifeController.NewSetting.NotifyMessageTitle; var smsMsg = $@"{ServiceLifeController.NewSetting.NotifyMessageContent}{Environment.NewLine}" + $"The <{e.KeepService.Service.Name}> process is [{e.NewStatus}]. {Environment.NewLine}"; SendNotify(e, emailSubject, emailMsg, smsMsg); #endregion #region Keep Service Stablity Status try { // Keep service status on a stable state which is selected by user if (e.KeepService.KeepStatusOn != ServiceStableStatus.None) { WindowsEventLog.WriteInfoLog($"Keep service status is ON for '{e.KeepService.Service.Name}'."); if ((int)e.KeepService.KeepStatusOn != (int)e.NewStatus) { WindowsEventLog.WriteInfoLog( $"Tying to keep '{e.KeepService.Service.Name}' status on {e.KeepService.KeepStatusOn} state..."); var result = false; switch (e.KeepService.KeepStatusOn) { case ServiceStableStatus.Running: result = ServiceInstallHelper.StartService(e.KeepService.Service.Name); break; case ServiceStableStatus.Stopped: result = ServiceInstallHelper.StopService(e.KeepService.Service.Name); break; case ServiceStableStatus.Paused: result = ServiceInstallHelper.PauseService(e.KeepService.Service.Name); break; } if (result) // success { WindowsEventLog.WriteInfoLog($"The '{e.KeepService.Service.Name}' status rollbacked on {e.KeepService.KeepStatusOn} stable state successfull"); #region Send Notify emailSubject = $"{e.KeepService.Service.Name} Rollbacked to {e.KeepService.KeepStatusOn} state Successfully"; emailMsg = $"<p style='color: #90EE90'>The <strong>{e.KeepService.Service.Name}</strong> process be rollbacked to <strong>{e.KeepService.KeepStatusOn}</strong> Successfully.</p>"; smsMsg = $@"Ok !{Environment.NewLine}" + $"The '{e.KeepService.Service.Name}' process be rollbacked to '{e.KeepService.KeepStatusOn}' Successfully.{Environment.NewLine}"; SendNotify(e, emailSubject, emailMsg, smsMsg); #endregion } else // fail { WindowsEventLog.WriteWarningLog($"The '{e.KeepService.Service.Name}' status can not rollbacked, and state is still on {e.NewStatus} !!!"); #region Send Notify emailSubject = $"{e.KeepService.Service.Name} Rollback to {e.KeepService.KeepStatusOn} state Failed!!"; emailMsg = $"<p style='color: #CD5C5C'>The <strong>{e.KeepService.Service.Name}</strong> process Rollbacking to <strong>{e.KeepService.KeepStatusOn}</strong> failed!!!</p>"; smsMsg = $@"Fail !!!{Environment.NewLine}" + $"The '{e.KeepService.Service.Name}' process can not rollbacked, and state is still on {e.NewStatus} !!!. {Environment.NewLine}"; SendNotify(e, emailSubject, emailMsg, smsMsg); #endregion } } else { WindowsEventLog.WriteInfoLog( $"The '{e.KeepService.Service.Name}' process status is stable state({e.KeepService.KeepStatusOn}), Now."); } } else { WindowsEventLog.WriteInfoLog($"Keep service status is OFF for '{e.KeepService.Service.Name}' !!!"); } } catch (Exception exp) { WindowsEventLog.WriteErrorLog($"Error in Keep service status on stable state by this Message: {exp.Message}"); } #endregion }
protected override void OnStart(string[] args) { ServiceLifeController.ServiceStatusChanged += ServiceLifeController_ServiceStatusChanged; ServiceLifeController.StartLifeCycleController(); WindowsEventLog.WriteInfoLog($"{ServiceName} Starting..."); }
private void SendNotify(ServiceNotifyEventArgs e, string emailSubject, string emailMessage, string smsMessage) { var preEmailMsg = (Debugger.IsAttached ? "<h3 style='color: #CD5C5C;'>Message sent in <strong>Developer</strong> mode</h3><br/>" : "") + $"<h2>{ServiceLifeController.NewSetting.NotifyMessageContent}</h2><br/>"; var postEmailMsg = $"<br/><br/><hr/><h5>Server Name is <strong>{Environment.MachineName}</strong></h5>"; emailMessage = preEmailMsg + emailMessage + postEmailMsg; var preSmsMsg = Debugger.IsAttached ? $"Message sent in [Developer] mode. {Environment.MachineName}" : ""; var postSmsMsg = $"Server Name is [{Environment.MachineName}]"; smsMessage = preSmsMsg + smsMessage + postSmsMsg; #region Send email to receivers try { //========================= Send Email to all of receivers =================================== if (ServiceLifeController.NewSetting.SendEmailNotifyEnable) { var email = new EmailModel(); email.Message = emailMessage; email.From = ServiceLifeController.NewSetting.SenderEmailAddress; email.SenderPassword = ServiceLifeController.NewSetting.GetSenderEmailNoHashPassword(); email.Subject = emailSubject; email.To = ServiceLifeController.NewSetting.ReceiverEmails; email.EmailHost = ServiceLifeController.NewSetting.EmailHost; email.EmailHostPort = ServiceLifeController.NewSetting.EmailHostPort; email.SendEmail(); } //============================================================================================ } catch (Exception exp) { WindowsEventLog.WriteErrorLog($"Exception in ServiceLifeController_ServiceStatusChanged event (send email): {exp.Message}"); } #endregion #region Send SMS to receivers try { //========================= Send SMS to all of receivers =================================== if (ServiceLifeController.NewSetting.SendSmsEnable) { var results = new SmsManager.SmsHelper().SendManySms( ServiceLifeController.NewSetting.SmsServiceUsername, ServiceLifeController.NewSetting.GetSmsServiceNoHashPassword(), smsMessage, ServiceLifeController.NewSetting.SmsSenderNumber, ServiceLifeController.NewSetting.SmsReceiverMobilesNo.ToArray()); for (var i = 0; i < results.Count; i++) { if (results[i].Retrieval == SmsManager.Retrieval.Successful) { WindowsEventLog.WriteInfoLog($"An SMS send to {results[i].ToNumber} by status: {results[i].Status} , recId: {results[i].RecId}"); } else { WindowsEventLog.WriteWarningLog($"An SMS can't send to {results[i].ToNumber}, status: {results[i].Status} , recId: {results[i].RecId}"); } } } //============================================================================================ } catch (Exception exp) { WindowsEventLog.WriteErrorLog($"Exception in ServiceLifeController_ServiceStatusChanged event (send sms): {exp.Message}"); } #endregion }
public static void SelectWhatDoing(this ServiceBase[] services, string[] args) { if (!services.Any()) { Environment.Exit(0); } string serviceName = services[0].ServiceName; if (args.Any()) { foreach (string arg in args) { switch (arg.ToLower()) { case "/d": case "/debug": case "-debug": case "--debug": { if (!IsAdmin()) { RestartElevated(ExePath, args); System.Environment.Exit(1); } services.LoadServices(); } break; case "/i": case "/install": case "-install": case "--install": SafeInstallService(serviceName, args); break; case "/u": case "/uninstall": case "-uninstall": case "--uninstall": SafeUninstallService(serviceName, args); break; default: WindowsEventLog.WriteErrorLog($@"\n'{arg}' arguments is not defined."); break; } } } else { if (Environment.UserInteractive) // Install Service { WindowsEventLog.WriteInfoLog(@"Service executed in UserInteractive mode"); if (!IsAdmin()) { WindowsEventLog.WriteInfoLog(@"Service go to executed in Run As Admin"); RestartElevated(ExePath, args); System.Environment.Exit(1); } WindowsEventLog.WriteInfoLog(@"Service in Run As Admin mode"); SafeInstallService(serviceName); // Run Service StartService(serviceName); } else // Service Running ... { ServiceBase.Run(services.ToArray()); } } }