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));
                }
            }
        }
        private void btnFetchLogs_Click(object sender, EventArgs e)
        {
            IEnumerable <Log> logs = null;

            if (dtpFrom.Checked)
            {
                logs = WindowsEventLog.GetEntryCollection(dtpFrom.Value, dtpTo.Checked ? dtpTo.Value : DateTime.Now, chkErrors.Checked, chkWarnings.Checked,
                                                          chkInformations.Checked, chkAuditSuccess.Checked, chkAuditFailure.Checked);
            }
            else if (dtpTo.Checked)
            {
                logs = WindowsEventLog.GetEntryCollection(dtpTo.Value.AddDays(-30), dtpTo.Value, chkErrors.Checked, chkWarnings.Checked,
                                                          chkInformations.Checked, chkAuditSuccess.Checked, chkAuditFailure.Checked);
            }
            else
            {
                logs = WindowsEventLog.GetEntryCollection(chkErrors.Checked, chkWarnings.Checked,
                                                          chkInformations.Checked, chkAuditSuccess.Checked, chkAuditFailure.Checked);
            }

            if (logs != null)
            {
                dgvLogs.DataSource = logs.ToDataTable();
            }
        }
Exemple #3
0
        public static void WriteToEventLogTest()
        {
            WindowsEventLog evt = null;

            try
            {
                _msg.Length = 0;
                _msg.Append("WriteToEventLogTest started ...\r\n");
                Program._messageLog.WriteLine(_msg.ToString());

                evt = new WindowsEventLog(WindowsEventLog.EventLogName.Application, ".", "PFApps");

                evt.WriteEntry("Test message from testprog ... yes indeed!", WindowsEventLog.WindowsEventLogEntryType.Information);
            }
            catch (System.Exception ex)
            {
                _msg.Length = 0;
                _msg.Append(AppGlobals.AppMessages.FormatErrorMessage(ex));
                Program._messageLog.WriteLine(_msg.ToString());
                AppMessages.DisplayErrorMessage(_msg.ToString(), _saveErrorMessagesToAppLog);
            }
            finally
            {
                _msg.Length = 0;
                _msg.Append("\r\n... WriteToEventLogTest finished.");
                Program._messageLog.WriteLine(_msg.ToString());
            }
        }
        protected override void OnShutdown()
        {
            base.OnShutdown();

            WindowsEventLog.WriteInfoLog($"The {Environment.MachineName} server will be turned off.");
            ServiceLifeController.WillBeTurnOff();
        }
 private void AreEqual(WindowsEventLog exp, WindowsEventLog act)
 {
     if (exp != null)
     {
         AreEqual(exp.DataSources, act.DataSources);
     }
 }
Exemple #6
0
 protected void Application_Start(object sender, EventArgs e)
 {
     WindowsEventLog.AddEvent("WebDav Application_Start()", 9999);
     IoCSetup.ForceLoad(typeof(EC.Core.Common.ForceLoad));
     BootstrapContainer();
     SetupServices();
 }
        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);
            }
        }
Exemple #8
0
        /// <summary>
        /// If the condition is false, log an error in the Windows Event Log. In a
        /// DEBUG build, an assertion failure will also cause the server to shut
        /// down.
        /// </summary>
        /// <param name="condition">Boolean to check</param>
        /// <param name="message">Message for event log</param>
        /// <exception cref="AssertException">Throw exception if assert fails (condition == <c>false</c>)</exception>

        public static void Assert(bool condition, string message)
        {
            if (condition)
            {
                return;
            }
            string msg = String.Format("{0} - Assertion Failure: {1}", DebugUtils.GetLocationFromStack(2), message);

            WindowsEventLog.AddEvent(msg, WindowsEventLog.DBCAssertion);
            ShutdownIfNeededAndThrow(msg);
        }
Exemple #9
0
        /// <summary>
        /// Check if the parameter <c>obj</c> is <c>null</c>. If <c>obj</c> is <c>null</c>,
        /// write an error to the Windows Event Log. In a DEBUG build, an assertion failure
        /// will also cause the server to shut down.
        /// </summary>
        /// <param name="obj">Object to check.</param>
        /// <param name="message">Message for the log if the parameter <c>obj</c> is <c>null</c>.</param>
        /// <exception cref="AssertException">Throw exception if object is <c>null</c></exception>

        public static void NonNull <T>(T obj, string message)
        {
            if (obj != null)
            {
                return;
            }
            string msg = String.Format("{0} - Null check failure: {1}", DebugUtils.GetLocationFromStack(2), message);

            WindowsEventLog.AddEvent(msg, WindowsEventLog.DBCNonNull);
            ShutdownIfNeededAndThrow(msg);
        }
Exemple #10
0
        /// <summary>
        /// Initiates IOC
        /// </summary>
        /// <remarks>
        /// IoCSetupForceLoad() deals with the problem that the app is so loosely
        /// coupled that it won't bother loading some assemblies because it doesn't
        /// see direct references to this.
        /// </remarks>

        private void BootstrapContainer()
        {
            try
            {
                container = IoCSetup.Run("EC WebDav Application Starting", "EC-Web-Dav");
            }
            catch (Exception ex)
            {
                var msg = String.Format("EC WebDav Application Startup (BootstrapContainer) - Unexpected Exception [{0}]", ex.Message.ToString());
                WindowsEventLog.AddEvent(msg, WindowsEventLog.FatalError);
            }
        }
 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);
 }
        protected override void OnIncomingError(ExceptionContext exceptionContext, IHubIncomingInvokerContext invokerContext)
        {
            string message = string.Format("=> Exception {0}", exceptionContext.Error.Message);

            if (exceptionContext.Error.InnerException != null)
            {
                message += "\n\t=> Inner Exception " + exceptionContext.Error.InnerException.Message;
            }

            WindowsEventLog.WriteErrorLog(message);

            base.OnIncomingError(exceptionContext, invokerContext);
        }
Exemple #14
0
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main(string[] args)
        {
            WindowsEventLog.CreateEventLog();

            ServiceBase[] ServicesToRun;

            ServicesToRun = new ServiceBase[]
            {
                new SignalRService()
            };

            //ServiceBase.Run(ServicesToRun);
            ServicesToRun.SelectWhatDoing(args);
        }
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main(string[] args)
        {
            WindowsEventLog.EventLogName       = SharedLinks.EventLogName;
            WindowsEventLog.EventLogSourceName = SharedLinks.EventLogSource;
            WindowsEventLog.CreateEventLog();

            var servicesToRun = new ServiceBase[]
            {
                new SLCService()
            };

            //ServiceBase.Run(servicesToRun);
            servicesToRun.SelectWhatDoing(args);
        }
        public static void NotifyStoppedCoveredServices()
        {
            lock (SyncObj)
            {
                var allServices = ServicesHelper.GetAllServices(); // all services
                try
                {
                    foreach (var keepService in NewSetting.CoveredServices)
                    {
                        // find any new state of covered services
                        var serviceNewStatus =
                            allServices.FirstOrDefault(x => x.Name.Equals(keepService.Service.Name, StringComparison.CurrentCultureIgnoreCase))?.Status;

                        // find any old state of covered services
                        var serviceOldStatus =
                            OldSetting.CoveredServices.FirstOrDefault(s => s.Service.Name.Equals(keepService.Service.Name, StringComparison.CurrentCultureIgnoreCase))?.Service.Status;

                        // set new state to new setting service
                        keepService.Service.Status = serviceNewStatus ?? ServiceControllerStatus.Stopped;

                        // the service stopped just now!!!
                        ServiceControllerStatusChanging newStatus;
                        Enum.TryParse(serviceNewStatus.ToString(), true, out newStatus);

                        // if status changed and identify status changing...
                        if (serviceNewStatus != serviceOldStatus)
                        {
                            if (NewSetting.NotifyJustStatusChangingTo.HasFlag(newStatus))
                            {
                                OnServiceStatusChanged(new ServiceNotifyEventArgs(keepService, serviceNewStatus ?? ServiceControllerStatus.Stopped));
                            }
                        }
                    }
                }
                catch (Exception exp)
                {
                    WindowsEventLog.WriteErrorLog($"Exception in ServiceLifeControllerService: {exp.Message}");
                }
                finally
                {
                    if (allServices != null)
                    {
                        GC.SuppressFinalize(allServices);
                    }

                    OldSetting = NewSetting;
                }
            }
        }
        public void WindowsEventLog_Constructor_CreatesWithExpectedInformation()
        {
            // Arrange
            var logName     = "foo";
            var machineName = "bar";
            var sourceName  = "blah";

            // Act
            var windowsEventLog = new WindowsEventLog(logName, machineName, sourceName);

            // Assert
            Assert.NotNull(windowsEventLog.DiagnosticsEventLog);
            Assert.Equal(logName, windowsEventLog.DiagnosticsEventLog.Log);
            Assert.Equal(machineName, windowsEventLog.DiagnosticsEventLog.MachineName);
            Assert.Equal(sourceName, windowsEventLog.DiagnosticsEventLog.Source);
        }
Exemple #18
0
        public void GivenWindowsEventLogAndDefaultEntryTypeShouldWriteEntry()
        {
            const string source    = "source";
            const string message   = "message";
            EventType    eventType = new EventType();

            LogAuthorFake   logAuthorFake   = new LogAuthorFake();
            WindowsEventLog windowsEventLog = new WindowsEventLog(logAuthorFake);

            windowsEventLog.WriteEntry(source, message, eventType);

            logAuthorFake.LogEntries().Count.Should().Be(1);
            logAuthorFake.LogEntries().First().Source().Should().Be(source);
            logAuthorFake.LogEntries().First().Message().Should().Be(message);
            logAuthorFake.LogEntries().First().EventType().Should().Be(eventType);
        }
 public void DeleteEventSource(string eventSourceName)
 {
     try
     {
         if (WindowsEventLog.SourceExists(eventSourceName))
         {
             WindowsEventLog.DeleteEventSource(eventSourceName);
             if (WindowsEventLog.SourceExists(eventSourceName) == false)
             {
                 _msg.Length = 0;
                 _msg.Append("Event Source ");
                 _msg.Append(eventSourceName);
                 _msg.Append(" delete succeeded.");
                 WriteMessageToLog(_msg.ToString());
             }
             else
             {
                 _msg.Length = 0;
                 _msg.Append("Event Source ");
                 _msg.Append(eventSourceName);
                 _msg.Append(" delete failed.");
                 WriteMessageToLog(_msg.ToString());
             }
         }
         else
         {
             _msg.Length = 0;
             _msg.Append("Event Source ");
             _msg.Append(eventSourceName);
             _msg.Append(" not found. No delete needed.");
             WriteMessageToLog(_msg.ToString());
         }
     }
     catch (System.Exception ex)
     {
         _msg.Length = 0;
         _msg.Append(AppGlobals.AppMessages.FormatErrorMessage(ex));
         _msg.Append(Environment.NewLine);
         _msg.Append("Caller must have elevated security permissions (e.g. use Run As Administrator) to create and delete event sources and event logs.");
         WriteMessageToLog(_msg.ToString());
         AppMessages.DisplayErrorMessage(_msg.ToString(), true);
     }
     finally
     {
         ;
     }
 }
Exemple #20
0
        /// <summary>
        /// Shut down the application. This involves shutting down any background threads and then releasing the
        /// IoC container that was allocated in IoCSetup.Run().
        /// </summary>

        public static void ShutdownThreadsAndReleaseContainer(string shutdownMsg)
        {
            if (ShuttingDown && Logger != null)
            {
                Logger.InfoFormat("IoCSetup::ShutdownThreadsAndReleaseContainer[{0}] - Re-entrant call. Stack = {1}", ContainerName, DebugUtils.GetStackTrace()); return;
            }
            ShuttingDown = true;

            if (Logger != null)
            {
                string msg = string.Format("IoCSetup::Shutdown[{0}] - {1}", ContainerName, shutdownMsg);
                Logger.Info(msg);
            }

            ShutdownBackgroundThreads();
            MainContainer.Dispose();
            WindowsEventLog.AddEvent(string.Format("IoCSetup::Shutdown[{0}] threads stopped and container disposed.", ContainerName), WindowsEventLog.Info);
        }
Exemple #21
0
        /// <summary>
        /// Initialize the Castle/Windsor IoC system. This includes setting up common facilities
        /// as well as registering components from all assemblies in the directory the application
        /// is executing from.
        /// </summary>
        /// <remarks>
        /// Originally this was called only once on application startup and a single container
        /// was used for the lifetime of the application. However, due to the way EF migration
        /// works, it became necessary to allocate new containers that would only be used in the
        /// context of EF migrations. These containers are assumed to be temporary in existence
        /// and it is also assumed that they should not have any background services
        /// associated with them. Thus, the suppressStartable parameter is interpreted to mean
        /// the caller is asking for a temporary-use container which has the effect
        /// both of suppressing the starting of IStartable components, but also of not storing
        /// the new container in the static member variable which is used to track the
        /// applications main container.
        /// </remarks>
        /// <remarks>
        /// RegisterCommonFacilities() must be called immediately on the newly created container
        /// because it sets up things like logging that we use every else.
        /// </remarks>
        /// <param name="startMsg">A startup message to place in the log</param>
        /// <returns>the initialized Windsor container</returns>

        public static IWindsorContainer Run(string startMsg, string containerName, bool suppressStartable = false)
        {
            WindowsEventLog.AddEvent(string.Format("IOCSetup.Run has been called for container name {0} (suppressStartable={1})", containerName, suppressStartable), WindowsEventLog.Info);
            ContainerName = containerName;
            var newContainer = new WindsorContainer();

            newContainer.Kernel.ComponentCreated += Kernel_ComponentCreated;
            RegisterCommonFacilities(newContainer, suppressStartable);
            DBC.Assert(MainContainer == null, String.Format("IoCSetup::Run[{0}] - Duplicate main container", containerName));
            MainContainer = newContainer;
            Logger        = newContainer.Resolve <ILogger>();
            Logger.Info(startMsg);
            DeactivatePropertyInjection(newContainer);
            SetupAssemblyLoadHook();
            IList <Assembly> loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();

            loadedAssemblies.ForEach(a => LogAssemblyName(a, "initial"));
            RegisterAssembliesForIOC(newContainer, loadedAssemblies);
            return(newContainer);
        }
Exemple #22
0
        /// <summary>
        /// Shut down the IoC container and exit the application/process. This will also cause all
        /// component instances to be released and all startable components to be stopped. This call
        /// should never return because it causes the process to exit with <paramref name="exitCode"/>
        /// </summary>
        /// <remarks>
        /// <para>
        /// We call Environment.Exit() here because there are threads running which we don't have
        /// direct control over and which don't seem to get stopped when we dispose the container.
        /// For example, we have observed AsynAppender threads continuing to run after dispose on
        /// the container has returned. This probably shouldn't be the case, but it would be time
        /// consuming to track down why. If we don't exit here, then the process may not exit due
        /// to these running threads.
        /// </para>
        /// <para>
        /// We have to call Exit() in a separate thread because the SCM complains if you call
        /// Exit() on its thread (and when you stop a service via the SCM it is the SCM's thread
        /// that is calling into this code).
        /// </para>
        /// <para>
        /// There is an interesting deadlock scenario that ShutdownStoppables() needs to avoid.
        /// If the thread calling Shutdown() is the background thread for an object bearing the
        /// IBackgroundThread interface, and it tries to call Stop() on the instance for which it
        /// is a background thread, then a deadlock results (because it is trying to stop itself).
        /// So ShutdownStoppeables() needs to avoid this scenario.
        /// </para>
        /// <para>
        /// We should try to stop all incoming requests, and ensure that all in-process requests
        /// are complete prior to calling Dispose on the container. This is not implemented currently.
        /// </para>
        /// </remarks>
        /// <param name="shutdownMsg">The shutdown message to log before exiting.</param>
        /// <param name="exitCode">Exit code to stop the system (any code other than 0 for any error occurred).</param>

        public static void ShutdownAndExit(string shutdownMsg, int exitCode)
        {
            try
            {
                ShutdownThreadsAndReleaseContainer(shutdownMsg);

                if (exitCode != 0)
                {
                    string msg = string.Format("IoCSetup::Shutdown[{0}] - {1} {2}", ContainerName, shutdownMsg, string.Format("Stack = {0}", DebugUtils.GetStackTrace()));
                    WindowsEventLog.AddEvent(msg, WindowsEventLog.FatalError);
                }
            }
            catch (Exception ex)
            {
                var msg = String.Format("IoCSetup::Shutdown[{0}]: Unexpected exception Msg={1} Ex = {2}", ContainerName, shutdownMsg, ex);
                WindowsEventLog.AddEvent(msg, WindowsEventLog.FatalError);
            }

            Task.Factory.StartNew(() => Environment.Exit(exitCode));
        }
Exemple #23
0
        private static bool LoggedIntoEventlog(Icon popupIcon, string infoMessage)
        {
            if (WindowsServiceHelper.IsRunningInServiceContext)
            {
                if (popupIcon == SystemIcons.Error)
                {
                    WindowsEventLog.LogError(infoMessage);
                }
                else if (popupIcon == SystemIcons.Warning)
                {
                    WindowsEventLog.LogWarning(infoMessage);
                }
                else
                {
                    WindowsEventLog.LogInformation(infoMessage);
                }
                return(true);
            }

            return(false);
        }
        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 static void LoadSettingData()
        {
            try
            {
                var path = FileManager.DefaultApplicationDataPath;

                var settingJson = FileManager.ReadFileSafely(path);

                if (settingJson == null)
                {
                    return;
                }

                // exchange new by old setting
                NewSetting = JsonConvert.DeserializeObject <SettingModel>(settingJson);
            }
            catch (Exception exp)
            {
                WindowsEventLog.WriteErrorLog($"Exception in ServiceLifeController: {exp.Message}");
            }
        }
Exemple #26
0
        protected void Application_Error(object sender, EventArgs e)
        {
            //Log the Error
            Exception ex     = Server.GetLastError();
            ILogger   logger = null;

            try
            {
                if (ex != null)
                {
                    string errMsg      = string.Format("Unhandled top-level error: {0}", ex.ToString());
                    string innerErrMsg = ex.InnerException != null?string.Format("Unhandled top-level error (inner): {0}", ex.InnerException.Message) : "No inner exception";

                    // Event logs...
                    WindowsEventLog.AddEvent(string.Format("WebDav Global.Application_Error(): {0}", errMsg), 9999);
                    if (ex.InnerException != null)
                    {
                        WindowsEventLog.AddEvent(string.Format("WebDav Global.Application_Error(): {0}", innerErrMsg), 9999);
                    }

                    // File log...
                    logger = container.Resolve <ILogger>();
                    logger.Error(errMsg);
                    if (ex.InnerException != null)
                    {
                        logger.ErrorFormat("WebDav Global.Application_Error(): {0}", innerErrMsg);
                    }
                }
                else
                {
                    WindowsEventLog.AddEvent("WebDav Global.Application_Error(): No exception found", 9999);
                }
            }
            finally { if (logger != null)
                      {
                          container.Release(logger);
                      }
            }
        }
 private void btnClearLogs_Click(object sender, EventArgs e)
 {
     WindowsEventLog.DeleteCurrentSource();
     btnFetchLogs.PerformClick();
 }
        static void Main(string[] args)
        {
            try
            {
                Logging.LogManager.Initialize("Deployment");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Failed to initialize logger: {ex}");
#if DEBUG
                Console.ReadKey();
#endif
                ExitInstallation("Failed to intialize Logger", ExitCode.FailedToInitilizeLogger);
            }

            _logger.Info($"Initialized {Namespace} v{Version}");

            // This has to happen quite early as it can take some time for the eventlog to be fully registered
            _logger.Trace("Ensuring WindowsEventLog ...");
            WindowsEventLog.Ensure();

            _logger.Trace("Trying to read settings...");

            if (args.Length != 2)
            {
                ExitInstallation("Invalid command line arguments. Use: -i [XML] or -u [XML]", ExitCode.MissingRequiredParameter);
            }

            var settingsPath = Path.GetFullPath(args[1]);
            _logger.Trace($"Searching for settings file in {settingsPath}");

            if (!File.Exists(settingsPath))
            {
                ExitInstallation("settings.xml is missing!", ExitCode.SettingsFileMissing);
            }

            var arguments        = args.ToList();
            var isInstallation   = arguments.Any(argument => argument.ToLower() == "--install" || argument.ToLower() == "-i");
            var isUninstallation = arguments.Any(argument => argument.ToLower() == "--uninstall" || argument.ToLower() == "-u");

            DeploymentEnvironmentVariables.RootDirectory = Path.GetDirectoryName(settingsPath);
            _logger.Info($"DeploymentRootDirectory: {DeploymentEnvironmentVariables.RootDirectory}");

            EnvironmentVariables.Configuration = ReadXml <Configuration>(settingsPath);
            _logger.Trace("Successfully read settings");

            _logger.Info("Verifying install dependencies ...");
            _logger.Info($"IsAdministrator: {EnvironmentVariables.IsAdministrator}");
            _logger.Info($"IsElevated: {EnvironmentVariables.IsElevated}");
            if (!EnvironmentVariables.IsElevated)
            {
                ExitInstallation("Program has to be run as Administrator to function properly!", ExitCode.NotElevated);
            }

            try
            {
                _logger.Info($"DT-Installation Path: {EnvironmentVariables.DeploymentToolkitInstallPath}");
            }
            catch (DeploymentToolkitInstallPathNotFoundException)
            {
                ExitInstallation($"Could not get installation path of the deployment toolkit", ExitCode.DeploymentToolkitInstallPathNotFound);
            }

            _logger.Trace("Reading deployment settings ...");
            ApplyGlobalSettings();

            _logger.Trace("Parsing command line arguments...");

            if (isInstallation)
            {
                Install();
            }
            else
            {
                if (isUninstallation)
                {
                    Uninstall();
                }
                else
                {
                    ExitInstallation("Failed to install or uninstall. Neither install nor uninstall command line has been specified", ExitCode.MissingRequiredParameter);
                }
            }

            _logger.Info($"Ended {Namespace} v{Version}");
#if DEBUG
            Console.ReadKey();
#endif
            Environment.Exit(GlobalExitCode);
        }
        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 OnPause()
 {
     WindowsEventLog.WriteWarningLog($"{ServiceName} Paused.");
 }