Example #1
0
        public static bool ScheduleAutoStart(string taskKey, string taskSuffix, bool enableAutoStart, string command, string profileName, bool onBoot)
        {
            var taskName   = GetScheduledTaskName(TaskType.AutoStart, taskKey, taskSuffix);
            var taskFolder = TaskService.Instance.RootFolder.SubFolders.Exists(TaskFolder) ? TaskService.Instance.RootFolder.SubFolders[TaskFolder] : null;

            if (enableAutoStart)
            {
                // create the task folder
                if (taskFolder == null)
                {
                    try
                    {
                        taskFolder = TaskService.Instance.RootFolder.CreateFolder(TaskFolder, null, false);
                    }
                    catch (Exception ex)
                    {
                        _logger.Error($"{nameof(ScheduleAutoStart)} - Unable to create the Server Manager task folder. {ex.Message}\r\n{ex.StackTrace}");
                        return(false);
                    }
                }

                if (taskFolder == null)
                {
                    return(false);
                }

                var task           = taskFolder.Tasks.Exists(taskName) ? taskFolder.Tasks[taskName] : null;
                var taskDefinition = task?.Definition ?? TaskService.Instance.NewTask();

                if (taskDefinition == null)
                {
                    return(false);
                }

                Version.TryParse(AppUtils.GetDeployedVersion(), out Version appVersion);

                taskDefinition.Principal.LogonType = TaskLogonType.ServiceAccount;
                taskDefinition.Principal.RunLevel  = TaskRunLevel.Highest;

                taskDefinition.RegistrationInfo.Description = $"Server Auto-Start - {profileName}";
                taskDefinition.RegistrationInfo.Source      = "Server Manager";
                taskDefinition.RegistrationInfo.Version     = appVersion;

                taskDefinition.Settings.ExecutionTimeLimit = TimeSpan.FromHours(EXECUTION_TIME_LIMIT);
                taskDefinition.Settings.Priority           = ProcessPriorityClass.Normal;

                // Add a trigger that will fire after the machine has started
                if (onBoot)
                {
                    var triggers = taskDefinition.Triggers.OfType <BootTrigger>();
                    if (triggers.Count() == 0)
                    {
                        var trigger = new BootTrigger
                        {
                            Delay = TimeSpan.FromMinutes(1),
                            ExecutionTimeLimit = TimeSpan.FromHours(EXECUTION_TIME_LIMIT)
                        };
                        taskDefinition.Triggers.Add(trigger);
                    }
                    else
                    {
                        foreach (var trigger in triggers)
                        {
                            trigger.Delay = TimeSpan.FromMinutes(1);
                        }
                    }
                }
                else
                {
                    var triggers = taskDefinition.Triggers.OfType <LogonTrigger>();
                    if (triggers.Count() == 0)
                    {
                        var trigger = new LogonTrigger
                        {
                            Delay = TimeSpan.FromMinutes(1),
                            ExecutionTimeLimit = TimeSpan.FromHours(EXECUTION_TIME_LIMIT)
                        };
                        taskDefinition.Triggers.Add(trigger);
                    }
                    else
                    {
                        foreach (var trigger in triggers)
                        {
                            trigger.Delay = TimeSpan.FromMinutes(1);
                        }
                    }
                }

                // Create an action that will launch whenever the trigger fires
                taskDefinition.Actions.Clear();
                var action = new ExecAction
                {
                    Path      = command,
                    Arguments = string.Empty
                };
                taskDefinition.Actions.Add(action);

                try
                {
                    task = taskFolder.RegisterTaskDefinition(taskName, taskDefinition, TaskCreation.CreateOrUpdate, "SYSTEM", null, TaskLogonType.ServiceAccount);
                    return(task != null);
                }
                catch (Exception ex)
                {
                    _logger.Error($"{nameof(ScheduleAutoStart)} - Unable to create the ScheduleAutoStart task. {ex.Message}\r\n{ex.StackTrace}");
                }
            }
            else
            {
                if (taskFolder == null)
                {
                    return(true);
                }

                // Retrieve the task to be deleted
                var task = taskFolder.Tasks.Exists(taskName) ? taskFolder.Tasks[taskName] : null;
                if (task == null)
                {
                    return(true);
                }

                try
                {
                    // Delete the task
                    taskFolder.DeleteTask(taskName, false);
                    return(true);
                }
                catch (Exception ex)
                {
                    _logger.Error($"{nameof(ScheduleAutoStart)} - Unable to delete the ScheduleAutoStart task. {ex.Message}\r\n{ex.StackTrace}");
                }
            }

            return(false);
        }
Example #2
0
        public static bool ScheduleAutoUpdate(string taskKey, string taskSuffix, string command, int autoUpdatePeriod)
        {
            var taskName   = GetScheduledTaskName(TaskType.AutoUpdate, taskKey, taskSuffix);
            var taskFolder = TaskService.Instance.RootFolder.SubFolders.Exists(TaskFolder) ? TaskService.Instance.RootFolder.SubFolders[TaskFolder] : null;

            if (autoUpdatePeriod > 0)
            {
                // create the task folder
                if (taskFolder == null)
                {
                    try
                    {
                        taskFolder = TaskService.Instance.RootFolder.CreateFolder(TaskFolder, null, false);
                    }
                    catch (Exception ex)
                    {
                        _logger.Error($"{nameof(ScheduleAutoUpdate)} - Unable to create the Server Manager task folder. {ex.Message}\r\n{ex.StackTrace}");
                        return(false);
                    }
                }

                if (taskFolder == null)
                {
                    return(false);
                }

                var task           = taskFolder.Tasks.Exists(taskName) ? taskFolder.Tasks[taskName] : null;
                var taskDefinition = task?.Definition ?? TaskService.Instance.NewTask();

                if (taskDefinition == null)
                {
                    return(false);
                }

                Version.TryParse(AppUtils.GetDeployedVersion(), out Version appVersion);

                taskDefinition.Principal.LogonType = TaskLogonType.InteractiveToken;
                taskDefinition.Principal.RunLevel  = TaskRunLevel.Highest;

                taskDefinition.RegistrationInfo.Description = "Server Auto-Update";
                taskDefinition.RegistrationInfo.Source      = "Server Manager";
                taskDefinition.RegistrationInfo.Version     = appVersion;

                taskDefinition.Settings.ExecutionTimeLimit = TimeSpan.FromHours(EXECUTION_TIME_LIMIT);
                taskDefinition.Settings.Priority           = ProcessPriorityClass.Normal;

                // Add/Edit the trigger that will fire every x minutes
                var triggers = taskDefinition.Triggers.OfType <TimeTrigger>();
                if (triggers.Count() == 0)
                {
                    var trigger = new TimeTrigger
                    {
                        StartBoundary      = DateTime.Today.AddHours(DateTime.Now.Hour + 1),
                        ExecutionTimeLimit = TimeSpan.FromHours(EXECUTION_TIME_LIMIT),
                        Repetition         = { Interval = TimeSpan.FromMinutes(autoUpdatePeriod) },
                    };
                    taskDefinition.Triggers.Add(trigger);
                }
                else
                {
                    foreach (var trigger in triggers)
                    {
                        trigger.Repetition.Interval = TimeSpan.FromMinutes(autoUpdatePeriod);
                    }
                }

                // Create an action that will launch whenever the trigger fires
                taskDefinition.Actions.Clear();
                var action = new ExecAction
                {
                    Path      = command,
                    Arguments = Constants.ARG_AUTOUPDATE
                };
                taskDefinition.Actions.Add(action);

                try
                {
                    task = taskFolder.RegisterTaskDefinition(taskName, taskDefinition, TaskCreation.CreateOrUpdate, null, null, TaskLogonType.InteractiveToken);
                    return(task != null);
                }
                catch (Exception ex)
                {
                    _logger.Error($"{nameof(ScheduleAutoUpdate)} - Unable to create the ScheduleAutoUpdate task. {ex.Message}\r\n{ex.StackTrace}");
                }
            }
            else
            {
                if (taskFolder == null)
                {
                    return(true);
                }

                // Retrieve the task to be deleted
                var task = taskFolder.Tasks.Exists(taskName) ? taskFolder.Tasks[taskName] : null;
                if (task == null)
                {
                    return(true);
                }

                try
                {
                    // Delete the task
                    taskFolder.DeleteTask(taskName, false);
                    return(true);
                }
                catch (Exception ex)
                {
                    _logger.Error($"{nameof(ScheduleAutoUpdate)} - Unable to delete the ScheduleAutoUpdate task. {ex.Message}\r\n{ex.StackTrace}");
                }
            }

            return(false);
        }
Example #3
0
        public static bool ScheduleAutoShutdown(string taskKey, string taskSuffix, string command, TimeSpan?restartTime, DaysOfTheWeek daysOfTheWeek, string profileName, ShutdownType type)
        {
            var taskName   = GetScheduledTaskName(TaskType.AutoShutdown, taskKey, taskSuffix);
            var taskFolder = TaskService.Instance.RootFolder.SubFolders.Exists(TaskFolder) ? TaskService.Instance.RootFolder.SubFolders[TaskFolder] : null;

            if (restartTime.HasValue)
            {
                // create the task folder
                if (taskFolder == null)
                {
                    try
                    {
                        taskFolder = TaskService.Instance.RootFolder.CreateFolder(TaskFolder, null, false);
                    }
                    catch (Exception ex)
                    {
                        _logger.Error($"{nameof(ScheduleAutoShutdown)} - Unable to create the Server Manager task folder. {ex.Message}\r\n{ex.StackTrace}");
                        return(false);
                    }
                }

                if (taskFolder == null)
                {
                    return(false);
                }

                var task           = taskFolder.Tasks.Exists(taskName) ? taskFolder.Tasks[taskName] : null;
                var taskDefinition = task?.Definition ?? TaskService.Instance.NewTask();

                if (taskDefinition == null)
                {
                    return(false);
                }

                Version.TryParse(AppUtils.GetDeployedVersion(), out Version appVersion);

                taskDefinition.Principal.LogonType = TaskLogonType.InteractiveToken;
                taskDefinition.Principal.RunLevel  = TaskRunLevel.Highest;

                taskDefinition.RegistrationInfo.Description = $"Server Auto-Shutdown - {profileName}";
                taskDefinition.RegistrationInfo.Source      = "Server Manager";
                taskDefinition.RegistrationInfo.Version     = appVersion;

                taskDefinition.Settings.ExecutionTimeLimit = TimeSpan.FromHours(EXECUTION_TIME_LIMIT);
                taskDefinition.Settings.Priority           = ProcessPriorityClass.Normal;

                // Add/Edit the trigger that will fire every day at the specified restart time
                var triggers = taskDefinition.Triggers.OfType <WeeklyTrigger>().ToList();
                if (triggers.Count == 0)
                {
                    var trigger = new WeeklyTrigger
                    {
                        StartBoundary      = DateTime.Today.Add(restartTime.Value),
                        ExecutionTimeLimit = TimeSpan.FromHours(EXECUTION_TIME_LIMIT),
                        DaysOfWeek         = daysOfTheWeek,
                    };
                    taskDefinition.Triggers.Add(trigger);
                }
                else
                {
                    foreach (var trigger in triggers)
                    {
                        trigger.StartBoundary = DateTime.Today.Add(restartTime.Value);
                        trigger.DaysOfWeek    = daysOfTheWeek;
                    }
                }

                // remove any old triggers
                var oldTriggers = taskDefinition.Triggers.OfType <DailyTrigger>().ToList();
                if (oldTriggers.Count > 0)
                {
                    foreach (var oldTrigger in oldTriggers)
                    {
                        taskDefinition.Triggers.Remove(oldTrigger);
                    }
                }

                // Create an action that will launch whenever the trigger fires
                var arguments = string.Empty;
                switch (type)
                {
                case ShutdownType.Shutdown1:
                    arguments = Constants.ARG_AUTOSHUTDOWN1;
                    break;

                case ShutdownType.Shutdown2:
                    arguments = Constants.ARG_AUTOSHUTDOWN2;
                    break;

                default:
                    return(false);
                }

                taskDefinition.Actions.Clear();
                var action = new ExecAction
                {
                    Path      = command,
                    Arguments = $"{arguments}{taskKey}"
                };
                taskDefinition.Actions.Add(action);

                try
                {
                    task = taskFolder.RegisterTaskDefinition(taskName, taskDefinition, TaskCreation.CreateOrUpdate, null, null, TaskLogonType.InteractiveToken);
                    return(task != null);
                }
                catch (Exception ex)
                {
                    _logger.Error($"{nameof(ScheduleAutoShutdown)} - Unable to create the ScheduleAutoShutdown task. {ex.Message}\r\n{ex.StackTrace}");
                }
            }
            else
            {
                if (taskFolder == null)
                {
                    return(true);
                }

                // Retrieve the task to be deleted
                var task = taskFolder.Tasks.Exists(taskName) ? taskFolder.Tasks[taskName] : null;
                if (task == null)
                {
                    return(true);
                }

                try
                {
                    // Delete the task
                    taskFolder.DeleteTask(taskName, false);
                    return(true);
                }
                catch (Exception ex)
                {
                    _logger.Error($"{nameof(ScheduleAutoShutdown)} - Unable to delete the ScheduleAutoShutdown task. {ex.Message}\r\n{ex.StackTrace}");
                }
            }

            return(false);
        }