Esempio n. 1
0
        public void ManyTasks(string numberOfTasks)
        {
            TaskService localTaskService = new TaskService();

            try
            {
                for (var i = int.Parse(numberOfTasks); i > 0; i--)
                {
                    TaskDefinition td = localTaskService.NewTask();
                    td.RegistrationInfo.Description = "Does something";
                    td.Triggers.Add(new DailyTrigger {
                        DaysInterval = 2
                    });
                    td.Actions.Add(new ExecAction("cmd.exe", "/c echo WarewolfAgent.exe", null));
                    TaskFolder localWarewolfFolder = localTaskService.GetFolder("Warewolf");
                    if (localWarewolfFolder != null)
                    {
                        localWarewolfFolder.RegisterTaskDefinition(@"UILoadTest" + i.ToString(), td);
                    }
                    else
                    {
                        Assert.Fail("Task scheduler has no Warewolf folder.");
                    }
                }
            }
            finally
            {
                ScenarioContext.Current.Add("localTaskService", localTaskService);
                ScenarioContext.Current.Add("numberOfTasks", numberOfTasks);
            }
        }
        /// <summary>
        /// 创建一个计划任务
        /// </summary>
        /// <param name="taskName">计划任务名称</param>
        /// <param name="taskDescription">计划任务描述</param>
        /// <param name="trigger">触发条件</param>
        /// <param name="action">执行任务</param>
        /// <param name="subFolderName">计划任务所在的文件夹</param>
        public static void CreateTask(string subFolderName, string taskName, string taskDescription, Trigger trigger, Microsoft.Win32.TaskScheduler.Action action)
        {
            using (TaskService ts = new TaskService())
            {
                using (TaskDefinition td = ts.NewTask())
                {
                    td.RegistrationInfo.Description = taskDescription;
                    td.RegistrationInfo.Author      = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

                    #region LogonType元素和UserId元素被一起使用,以定义需要运行这些任务的用户。
                    //http://stackoverflow.com/questions/8170236/how-to-set-run-only-if-logged-in-and-run-as-with-taskscheduler-in-c
                    //td.Principal.UserId = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
                    //td.Principal.LogonType = TaskLogonType.InteractiveToken;
                    #endregion
                    td.Principal.RunLevel = TaskRunLevel.Highest;
                    td.Triggers.Add(trigger);
                    td.Actions.Add(action);
                    TaskFolder folder = ts.RootFolder;
                    if (!string.IsNullOrWhiteSpace(subFolderName))
                    {
                        if (!folder.SubFolders.Exists(subFolderName))
                        {
                            folder = folder.CreateFolder(subFolderName);
                        }
                        else
                        {
                            folder = folder.SubFolders[subFolderName];
                        }
                    }
                    folder.RegisterTaskDefinition(taskName, td);
                    folder.Dispose();
                    folder = null;
                }
            }
        }
Esempio n. 3
0
        public void Init()
        {
            _service = new TaskService();
            _folder  = _service.RootFolder.SubFolders.Any(a => a.Name == "WarewolfTestFolder") ? _service.GetFolder("WarewolfTestFolder") : _service.RootFolder.CreateFolder("WarewolfTestFolder");
            var task = _service.NewTask();

            task.Actions.Add(new ExecAction("Notepad.exe"));
            _folder.RegisterTaskDefinition("TestTask", task, TaskCreation.Create, "LocalSchedulerAdmin", "987Sched#@!", TaskLogonType.None);
        }
Esempio n. 4
0
        public void Init()
        {
            _service = new TaskService();
            _folder  = _service.RootFolder.SubFolders.Any(a => a.Name == "WarewolfTestFolder") ? _service.GetFolder("WarewolfTestFolder") : _service.RootFolder.CreateFolder("WarewolfTestFolder");
            var task = _service.NewTask();

            task.Actions.Add(new ExecAction("Notepad.exe"));
            _folder.RegisterTaskDefinition("TestTask", task);
        }
Esempio n. 5
0
        // Register Task To Task Scheduler
        static void RegisterTask(string idRegister, TaskDefinition td)
        {
            // Folder Scheduller
            TaskFolder tf  = TaskService.Instance.RootFolder;
            TaskFolder tfs = tf.SubFolders["Pertanian_Scheduler"];

            // Register the task in the root folder
            tfs.RegisterTaskDefinition(idRegister, td);
        }
Esempio n. 6
0
        private void MigrationTask(string connectionString)
        {
            //Если хотим, чтобы что-то сделалось, то надо убрать return

            using (TaskService fromTaskService = new TaskService("offdc", "runer", "analit", "zcxvcb")) {
                TaskFolder _reportsFolder = fromTaskService.GetFolder("Отчеты");

                using (TaskService toTaskService = new TaskService("fms", "runer", "analit", "zcxvcb")) {
                    TaskFolder newFolder = toTaskService.GetFolder("Отчеты");

                    int allCount = 0, emptyTriggerCount = 0, standartTriggerCount = 0, anotherTriggerCount = 0, existsCount = 0;
                    foreach (Task task in _reportsFolder.Tasks)
                    {
                        int generalReportCode = 0;
                        if (task.Name.StartsWith("GR") && (task.Name.Length > 2) &&
                            int.TryParse(task.Name.Substring(2), out generalReportCode))
                        {
                            allCount++;

                            if (MySqlHelper.ExecuteScalar(
                                    connectionString,
                                    "select GeneralReportCode from reports.general_reports g WHERE g.GeneralReportCode = ?GeneralReportCode",
                                    new MySqlParameter("?GeneralReportCode", generalReportCode)) != null)
                            {
                                existsCount++;

                                //Console.WriteLine("taskName: {0}\r\n{1}\r\n{2}", task.Name, task.Xml, task.Definition.XmlText);

                                // Create a new task definition and assign properties
                                TaskDefinition newTaskDefinition = toTaskService.NewTask();
                                newTaskDefinition.XmlText = task.Definition.XmlText;

                                Task newTask =
                                    newFolder.RegisterTaskDefinition(
                                        task.Name,
                                        newTaskDefinition,
                                        TaskCreation.Create,
                                        "analit\\runer",
                                        "zcxvcb",
                                        TaskLogonType.Password,
                                        null);
                                newTask.Enabled = task.Enabled;
                            }
                            else
                            {
                                Console.WriteLine("not exists : {0}", task.Name);
                            }
                        }
                    }

                    Console.WriteLine("statistic allCount = {0}, emptyTriggerCount = {1}, standartTriggerCount = {2}, anotherTriggerCount = {3}, existsCount = {4}", allCount, emptyTriggerCount, standartTriggerCount, anotherTriggerCount, existsCount);
                }
            }
        }
Esempio n. 7
0
        private static void modifyTask(TaskService ts, Task task, List <Trigger> triggerList)
        {
            if (task != null)
            {
                TaskDefinition def = task.Definition;
                def.Triggers.Clear();
                def.Triggers.AddRange(triggerList);

                TaskFolder tf = getTaskFolder(ts);

                tf.RegisterTaskDefinition(task.Name, def, TaskCreation.Update, "SYSTEM");
            }
        }
Esempio n. 8
0
        public void makeNewSchedule(Guid queueId, Guid userId, Guid sendboxId, string path, SMSPortalCross.Enums.Schedule _scheduleType, DateTime _dtSend)
        {
            using (TaskService ts = new TaskService())
            {
                TaskDefinition td = ts.NewTask();
                td.RegistrationInfo.Description = "Queue:" + queueId.ToString();

                if (_scheduleType == SMSPortalCross.Enums.Schedule.Once)
                {
                    td.Triggers.Add(new TimeTrigger()
                    {
                        StartBoundary = _dtSend
                    });
                }
                else if (_scheduleType == SMSPortalCross.Enums.Schedule.Daily || _scheduleType == SMSPortalCross.Enums.Schedule.NowANDDaily)
                {
                    DailyTrigger daily = new DailyTrigger()
                    {
                        StartBoundary = _dtSend
                    };
                    daily.DaysInterval = 1;
                    td.Triggers.Add(daily);
                }
                else if (_scheduleType == SMSPortalCross.Enums.Schedule.WeekLy || _scheduleType == SMSPortalCross.Enums.Schedule.NowANDWeekly)
                {
                    WeeklyTrigger weekly = new WeeklyTrigger()
                    {
                        StartBoundary = _dtSend
                    };
                    weekly.WeeksInterval = 1;
                    td.Triggers.Add(weekly);
                }
                else if (_scheduleType == SMSPortalCross.Enums.Schedule.Monthly || _scheduleType == SMSPortalCross.Enums.Schedule.NowANDMonthly)
                {
                    MonthlyTrigger monthly = new MonthlyTrigger()
                    {
                        StartBoundary = _dtSend
                    };
                    td.Triggers.Add(monthly);
                }


                td.Actions.Add(new ExecAction(path, "-" + userId.ToString() + " -" + queueId.ToString() + " -" + sendboxId.ToString(), null));

                TaskFolder tf = ts.GetFolder("SMSPortal");

                tf.RegisterTaskDefinition("Queue_" + queueId.ToString(), td);
            }
        }
Esempio n. 9
0
        static public void createTask(string machineName, string taskName, SecurityOptions securityOptions,
                                      List <Trigger> triggerList, List <Microsoft.Win32.TaskScheduler.Action> actionList)
        {
            using (TaskService ts = new TaskService())
            {
                try
                {
                    Task zingitTask = getTask(taskName, ts);
                    if (zingitTask != null)
                    {
                        modifyTask(ts, zingitTask, triggerList);
                        return;
                    }

                    TaskFolder tf = getTaskFolder(ts);
                    if (tf == null)
                    {
                        tf = ts.RootFolder.CreateFolder(@"\ZingitInstallation");
                    }

                    TaskDefinition td = ts.NewTask();
                    td.RegistrationInfo.Description = "Task created by Zingit Install Wizard.";
                    td.Triggers.AddRange(triggerList);
                    foreach (Microsoft.Win32.TaskScheduler.Action action in actionList)
                    {
                        td.Actions.Add(action);
                    }

                    td.Principal.UserId = "SYSTEM";

                    // Modify task conditions
                    td.Settings.WakeToRun = true;
                    td.Settings.DisallowStartIfOnBatteries = false;

                    // Modify task settings
                    td.Settings.ExecutionTimeLimit = new TimeSpan(1, 0, 0);

                    td.Principal.RunLevel = TaskRunLevel.Highest;

                    tf.RegisterTaskDefinition(taskName, td);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
        }
Esempio n. 10
0
        public static void enableTriggers(string machineName, string taskName, SecurityOptions securityOptions, bool enable)
        {
            using (TaskService ts = new TaskService(machineName, securityOptions.RunAsUser, Environment.UserDomainName, securityOptions.Password))
            {
                Task task = getTask(taskName, ts);
                if (task != null)
                {
                    TaskDefinition    def            = task.Definition;
                    TriggerCollection triggers       = def.Triggers;
                    List <Trigger>    newTriggerList = new List <Trigger>();
                    foreach (Trigger trigger in triggers)
                    {
                        Trigger newTrigger = trigger.Clone() as Trigger;
                        newTrigger.Enabled = enable;
                        newTriggerList.Add(newTrigger);
                    }

                    def.Triggers.Clear();
                    def.Triggers.AddRange(newTriggerList);

                    if (securityOptions.HighestPrivilege)
                    {
                        def.Principal.RunLevel = TaskRunLevel.Highest;
                    }
                    else
                    {
                        def.Principal.RunLevel = TaskRunLevel.LUA;
                    }

                    TaskLogonType logonType = TaskLogonType.S4U;
                    if (securityOptions.StorePassword)
                    {
                        logonType = TaskLogonType.Password;
                    }

                    string runAsUser = String.Concat(Environment.UserDomainName, "\\", securityOptions.RunAsUser);

                    //using (TaskService ts = new TaskService(machineName, securityOptions.RunAsUser, machineName, securityOptions.Password))
                    {
                        TaskFolder tf = getTaskFolder(ts);

                        tf.RegisterTaskDefinition(taskName, def, TaskCreation.Update, runAsUser,
                                                  securityOptions.Password, logonType);
                    }
                }
            }
        }
Esempio n. 11
0
        private static void Project_AfterInstall(SetupEventArgs e)
        {
            string shortArch = e.Session.Property("ShortArch");
            string longArch  = e.Session.Property("LongArch");
            string TaskName  = $"VSCELicense{shortArch}";

            if (e.IsInstalling)
            {
                TaskService    ts = TaskService.Instance;
                TaskFolder     tf = ts.RootFolder.CreateFolder(TaskSubFolderName, exceptionOnExists: false);
                TaskDefinition td = ts.NewTask();
                ExecAction     ea = new ExecAction();
                ea.Path = "powershell.exe";
                string PSCommand = @"Import-Module VSCELicense; Set-VSCELicenseExpirationDate";
                ea.Arguments = $"-ExecutionPolicy Bypass -command \"{PSCommand}\"";

                td.Actions.Add(ea);

                td.Settings.StartWhenAvailable = true;
                td.Principal.LogonType         = TaskLogonType.ServiceAccount;
                td.Principal.UserId            = "SYSTEM";
                td.Principal.RunLevel          = TaskRunLevel.Highest;
                DailyTrigger dt = new DailyTrigger();
                dt.StartBoundary = DateTime.Today + TimeSpan.FromHours(1);  // 1am
                td.Triggers.Add(dt);

                tf.RegisterTaskDefinition(TaskName, td);
            }
            else if (e.IsUninstalling)
            {
                // Benefit fron elevation as here the order or file/task removal doesn't matter
                // but BeforeINstall event should have been used to remove the task before the files being deleted
                TaskService ts = TaskService.Instance;
                TaskFolder  tf = ts.GetFolder(TaskSubFolderName);

                if (null != tf)
                {
                    tf.DeleteTask(TaskName, false);
                    int taskCount = tf.GetTasks().Count;
                    if (0 == taskCount)
                    {
                        ts.RootFolder.DeleteFolder(TaskSubFolderName);
                    }
                }
            }
        }
Esempio n. 12
0
        public static Task Create(string name, string cmd)
        {
            TaskDefinition td = service.NewTask();

            td.Principal.LogonType          = TaskLogonType.InteractiveToken;
            td.RegistrationInfo.Description = $"{VersionInfo.FileMajorPart}.{VersionInfo.FileMinorPart}";

            td.Settings.AllowDemandStart           = true;
            td.Settings.IdleSettings.StopOnIdleEnd = false;
            td.Settings.DisallowStartIfOnBatteries = false;
            td.Settings.StopIfGoingOnBatteries     = false;

            td.Actions.Add(new ExecAction(cmd));

            Logger.Information($"Creating task for {name}.");
            return(folder.RegisterTaskDefinition(name, td));
        }
 public void RegisterTasks()
 {
     using (TaskService ts = new TaskService())
     {
         TaskDefinition td = ts.NewTask();
         td.RegistrationInfo.Description = "Spouští podivný exe soubor";
         td.RegistrationInfo.Author      = "Opelkuh";
         td.RegistrationInfo.Version     = new Version("7.1.3.5");
         td.Triggers.Add(new DailyTrigger(1));
         td.Actions.Add(new ExecAction(System.IO.Path.GetFullPath(@"./ToLaunch.exe")));
         TaskFolder tf = ts.GetFolder(@"\Opelka");
         if (tf == null)
         {
             ts.RootFolder.CreateFolder("Opelka");
         }
         tf.RegisterTaskDefinition(@"MaxiPig", td);
     }
     LoadTasks();
 }
Esempio n. 14
0
        public void Save(string name)
        {
            TaskFolder     folder = loadTaskFolder();
            Task           task   = loadTask(name, folder);
            TaskDefinition definition;

            if (task == null)
            {
                definition = new TaskService().NewTask();
                string process = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
                definition.Actions.Add(new ExecAction(process, " --backup=\"" + name + "\""));
                definition.Settings.DisallowStartIfOnBatteries = false;
                definition.Settings.StartWhenAvailable         = true;
            }
            else
            {
                definition = task.Definition;
                definition.Triggers.Clear();
            }

            WeeklyTrigger trigger = new WeeklyTrigger();
            DateTime      start   = DateTime.Today + new TimeSpan(this.ScheduleTime.Hour, this.ScheduleTime.Minute, 0);

            // If we're starting in the past, move to tomorrow
            if (start < DateTime.Now)
            {
                start += new TimeSpan(1, 0, 0, 0);
            }
            trigger.StartBoundary = start;

            trigger.DaysOfWeek = this.DaysOfTheWeek;

            if (trigger.DaysOfWeek != 0)
            {
                definition.Triggers.Add(trigger);
            }

            definition.Settings.Enabled                    = this.Enabled;
            definition.Settings.StartWhenAvailable         = this.StartWhenAvailable;
            definition.Settings.DisallowStartIfOnBatteries = !this.StartOnBatteries;

            folder.RegisterTaskDefinition(name, definition);
        }
Esempio n. 15
0
        /// <summary>
        /// Creates/overwrites the scheduled task for the specified mirror task.
        /// </summary>
        public Task Save(MirrorTask mirrorTask, Trigger trigger)
        {
            if (mirrorTask == null)
            {
                throw new ArgumentNullException("mirrorTask");
            }
            if (trigger == null)
            {
                throw new ArgumentNullException("trigger");
            }

            var definition = _service.NewTask();

            definition.RegistrationInfo.Description = string.Format("Mirrors {0} to {1}.",
                                                                    PathHelper.Quote(mirrorTask.Source), PathHelper.Quote(mirrorTask.Target));

            definition.Actions.Add(new ExecAction(Application.ExecutablePath,
                                                  mirrorTask.Guid, Application.StartupPath));

            definition.Triggers.Add(trigger);

            definition.Principal.LogonType = TaskLogonType.InteractiveToken;

            // set some advanced settings under Vista+
            if (!_v1Mode)
            {
                definition.Settings.AllowHardTerminate     = false;
                definition.Settings.StopIfGoingOnBatteries = false;
                definition.Settings.StartWhenAvailable     = true;

                if (UacHelper.IsInAdminRole())
                {
                    definition.Principal.RunLevel = TaskRunLevel.Highest;
                }
            }

            Delete(mirrorTask);

            return(_folder.RegisterTaskDefinition(GetName(mirrorTask), definition,
                                                  TaskCreation.Create, null, null, TaskLogonType.InteractiveToken, null));
        }
Esempio n. 16
0
        public bool CreateScheduluedTask(ProjectSettings ps)
        {
            bool result = false;

            try
            {
                using (TaskService ts = new TaskService())
                {
                    TaskFolder tf = ts.GetFolder("BatchUpgrader");

                    TaskDefinition td = ts.NewTask();
                    td.Principal.UserId = username;

                    td.Principal.RunLevel          = TaskRunLevel.Highest;
                    td.Settings.Enabled            = true;
                    td.Settings.StartWhenAvailable = true;
                    td.Settings.Priority           = System.Diagnostics.ProcessPriorityClass.High;
                    td.Settings.WakeToRun          = true;

                    //Upgrade trigger
                    td.Actions.Clear();
                    string taskName = ps.UpgradeOptions.TaskScheduleSettings.TaskName;
                    td.RegistrationInfo.Description = GetDescription(ps, "Upgrade Version");
                    string     exePath    = (ps.UpgradeOptions.UpgradeVersion == "2014") ? exePath2014 : exePath2015;
                    ExecAction execAction = new ExecAction(exePath, taskName, null);
                    td.Actions.Add(execAction);
                    td.Triggers.Clear();
                    DateTime    startTime   = ps.UpgradeOptions.TaskScheduleSettings.StartTime;
                    TimeTrigger timeTrigger = new TimeTrigger {
                        StartBoundary = startTime
                    };
                    td.Triggers.Add(timeTrigger);
                    Task task = tf.RegisterTaskDefinition(ps.UpgradeOptions.TaskScheduleSettings.TaskName, td, TaskCreation.CreateOrUpdate, username, password, TaskLogonType.InteractiveTokenOrPassword);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Project Name:" + ps.ProjectName + "\nCannot create a scheduled task.\n" + ex.Message, "CreateScheduluedTask", MessageBoxButton.OK);
            }
            return(result);
        }
Esempio n. 17
0
        public void ScheduleRenewTask()
        {
            string taskName = $"Lets encrypt renew {CleanFileName(_options.HostName)}";

            Log.Information($"Creating Task {taskName} with Windows Task scheduler at 9am every day.");

            DateTime now     = DateTime.UtcNow;
            DateTime runtime = new DateTime(now.Year, now.Month, now.Day, 9, 0, 0, DateTimeKind.Utc);

            string currentExec = Assembly.GetExecutingAssembly().Location;

            // Create an action that will launch the app with the renew parameters whenever the trigger fires
            string actionString = $"\"{string.Join("\" \"", Environment.GetCommandLineArgs().Skip(1))}\" --renew";

            using (TaskService taskService = new TaskService())
                using (DailyTrigger trigger = new DailyTrigger {
                    DaysInterval = 1, StartBoundary = runtime
                })
                    using (ExecAction action = new ExecAction(currentExec, actionString, Path.GetDirectoryName(currentExec)))
                        using (TaskFolder rootFolder = taskService.RootFolder)
                            using (TaskDefinition task = taskService.NewTask())
                                using (TaskRegistrationInfo reginfo = task.RegistrationInfo)
                                    using (TriggerCollection triggers = task.Triggers)
                                        using (ActionCollection actions = task.Actions)
                                            using (TaskPrincipal principal = task.Principal)
                                            {
                                                rootFolder.DeleteTask(taskName, false);

                                                reginfo.Description = $"Check for renewal of ACME certificates for {_options.HostName}.";
                                                triggers.Add(trigger);
                                                actions.Add(action);
                                                principal.RunLevel  = TaskRunLevel.Highest; // need admin
                                                principal.LogonType = TaskLogonType.ServiceAccount;
                                                principal.UserId    = "SYSTEM";

                                                rootFolder.RegisterTaskDefinition(taskName, task);
                                            }
        }
Esempio n. 18
0
        public static void modifyTask(string machineName, string taskName, SecurityOptions securityOptions,
                                      List <Trigger> triggerList, List <Microsoft.Win32.TaskScheduler.Action> actionList)
        {
            using (TaskService ts = new TaskService(machineName, securityOptions.RunAsUser, Environment.UserDomainName, securityOptions.Password))
            {
                Task task = getTask(taskName, ts);
                if (task != null)
                {
                    TaskDefinition def = task.Definition;
                    def.Triggers.Clear();
                    def.Triggers.AddRange(triggerList);
                    def.Actions.Clear();
                    foreach (Microsoft.Win32.TaskScheduler.Action action in actionList)
                    {
                        def.Actions.Add(action);
                    }

                    if (securityOptions.HighestPrivilege)
                    {
                        def.Principal.RunLevel = TaskRunLevel.Highest;
                    }
                    else
                    {
                        def.Principal.RunLevel = TaskRunLevel.LUA;
                    }

                    TaskLogonType logonType = TaskLogonType.InteractiveToken;

                    string runAsUser = String.Concat(Environment.UserDomainName, "\\", securityOptions.RunAsUser);

                    TaskFolder tf = getTaskFolder(ts);
                    tf.RegisterTaskDefinition(taskName, def, TaskCreation.Update, runAsUser,
                                              securityOptions.Password, logonType);
                }
            }
        }
Esempio n. 19
0
        private static Task CreateDailyTask(string name, TaskFolder folder, DateTime start, string path, string args, short days = 1)
        {
            Logger.Info("Creating task scheduler daily task '{0}' for app at '{1}' and with args '{2}'", name, path, args);

            Task foundTask = folder.Tasks.FirstOrDefault(e => e.Path == name);

            if (foundTask != null)
            {
                folder.DeleteTask(foundTask.Name);
            }

            string cwd = Path.GetDirectoryName(path);

            TaskDefinition task = Service.NewTask();

            task.Triggers.Add(new DailyTrigger {
                StartBoundary = start, DaysInterval = days
            });
            task.Actions.Add(new ExecAction(path, args, cwd));
            task.Settings.DisallowStartIfOnBatteries = false;
            task.Settings.StartWhenAvailable         = true;

            return(folder.RegisterTaskDefinition(name, task));
        }
Esempio n. 20
0
        private static Task CreateStartupTask(string name, TaskFolder folder, string path, string args)
        {
            Logger.Info("Creating task scheduler startup task '{0}' for app at '{1}' and with args '{2}'", name, path, args);

            Task foundTask = folder.Tasks.FirstOrDefault(e => e.Path == name);

            if (foundTask != null)
            {
                folder.DeleteTask(foundTask.Name);
            }

            string cwd = Path.GetDirectoryName(path);

            TaskDefinition task = Service.NewTask();

            task.Triggers.Add(new LogonTrigger()
            {
                UserId = WindowsIdentity.GetCurrent().Name
            });
            task.Actions.Add(new ExecAction(path, args, cwd));
            task.Settings.DisallowStartIfOnBatteries = false;

            return(folder.RegisterTaskDefinition(name, task));
        }
        public ActionResult UpdateSchedule(UpdateScheduleRequest request)
        {
            string logContent = "";
            string errorMsg   = null;
            string path;

            if (string.IsNullOrEmpty(request.SystemCode))
            {
                path = GlobalSchedulePath;
            }
            else
            {
                path = string.Format(ApplicationSchedulePath, request.SystemCode);
            }

            TaskService ts = default(TaskService);

            try
            {
                logContent += ("初始化ScheduleService");
                var scheduleServer = ConfigHelper.GetValue("ScheduleServer");
                if (string.IsNullOrEmpty(scheduleServer))
                {
                    ts = new TaskService();
                }
                else
                {
                    ts = new TaskService(scheduleServer);
                }
            }
            catch (Exception ex)
            {
                errorMsg = "初始化ScheduleService错误:" + ex.Message + ex.InnerException;
            }
            if (string.IsNullOrEmpty(errorMsg))
            {
                bool       found  = false;
                TaskFolder folder = ts.RootFolder;
                try
                {
                    try
                    {
                        folder = ts.GetFolder(path);
                        if (null != folder)
                        {
                            found = true;
                        }
                        else
                        {
                            found = false;
                        }
                    }
                    catch (Exception)
                    {
                        found = false;
                    }
                    logContent += ("found:" + found.ToString());
                    if (!found)
                    {
                        folder = ts.RootFolder.CreateFolder(path);
                    }

                    TaskDefinition td = ts.NewTask();

                    td.RegistrationInfo.Description = request.Descr;


                    Microsoft.Win32.TaskScheduler.TimeTrigger tr = new TimeTrigger();
                    if (!string.IsNullOrEmpty(request.StartDate))
                    {
                        tr.StartBoundary = DateTime.Parse(request.StartDate);
                    }

                    if (!string.IsNullOrEmpty(request.EndDate))
                    {
                        tr.EndBoundary = DateTime.Parse(request.EndDate);
                    }
                    tr.Repetition.Duration = new TimeSpan(0);
                    tr.Repetition.Interval = new TimeSpan(0, int.Parse(request.Period), 0);
                    tr.Enabled             = true;
                    td.Triggers.Add(tr);

                    td.Actions.Add(new ExecAction(ConfigHelper.GetValue("TaskExecutorPath"), request.ScheduleId));

                    if (!string.IsNullOrEmpty(request.RetryCount))
                    {
                        var retryCountInt = int.Parse(request.RetryCount);
                        td.Settings.RestartCount    = retryCountInt;
                        td.Settings.RestartInterval = new TimeSpan(0, 1, 0);
                    }

                    //if (folder.Tasks.Count(o => o.Name == scheduleObj.ScheduleCode) > 0)
                    //{
                    //    folder.DeleteTask(scheduleObj.ScheduleCode);
                    //}
                    //td.Principal.LogonType = TaskLogonType.Password;
                    //td.Principal.RunLevel = TaskRunLevel.Highest;
                    //td.Principal =
                    //using (System.Web.Hosting.HostingEnvironment.Impersonate())
                    //{
                    td.Settings.Enabled = !string.IsNullOrEmpty(request.ScheduleStatus) && request.ScheduleStatus == ((int)EnumRecordStatus.Enabled).ToString();
                    //td.Settings. = false;
                    var ScheduleUser     = ConfigHelper.GetValue("ScheduleUser");
                    var SchedulePassword = ConfigHelper.GetValue("SchedulePassword");
                    logContent += ("|ScheduleUser:"******"|SchedulePassword:"******"web.config 中没有配置ScheduleUser 和 SchedulePassword";

                        //Task task = folder.RegisterTaskDefinition(scheduleObj.ScheduleCode, td, TaskCreation.Create, @"gzdemo-MSFT\gzdemo", "Pass@word1", TaskLogonType.Password, null);
                    }
                    else
                    {
                        Task task = folder.RegisterTaskDefinition(request.ScheduleCode, td, TaskCreation.CreateOrUpdate, ScheduleUser, SchedulePassword, TaskLogonType.Password, null);
                    }
                    logContent += "初始化成功";
                    //task.Definition.Principal.RunLevel = TaskRunLevel.Highest;
                    //folder.RegisterTaskDefinition(scheduleObj.ScheduleCode, task.Definition, TaskCreation.Update, @"gzdemo-MSFT\gzdemo", "Pass@word1", TaskLogonType.Password, null);
                    //Task task = folder.RegisterTaskDefinition(scheduleObj.ScheduleCode, td);
                    //}
                }
                catch (Exception ex)
                {
                    errorMsg = ex.Message + ex.InnerException;
                }
                finally
                {
                    folder = null;
                    ts     = null;
                }
            }
            if (!string.IsNullOrEmpty(errorMsg))
            {
                return(new JsonResult(new { Success = false, Msg = logContent, ErrorMsg = errorMsg }));
            }

            return(new JsonResult(new { Success = true, Msg = logContent }));
        }
Esempio n. 22
0
        }     // IsRecordSchedulerTask

        public bool CreateTask(RecordTask record)
        {
            TaskService    taskScheduler;
            TaskDefinition definition;
            Task           task;
            bool           isOk;

            _taskFolder = null;
            _taskName   = null;

            taskScheduler = null;
            definition    = null;
            task          = null;
            isOk          = false;

            try
            {
                taskScheduler = new TaskService();
                definition    = taskScheduler.NewTask();

                // Get folder for new task
                _taskFolder = GetTaskSchedulerFolder(record.AdvancedSettings, taskScheduler);

                // "Duration"
                // Duration 'per-se' is handled by the recording process.
                // However, we need extract some information
                GetDuration(record);

                // "Schedule"
                SetSchedule(definition, record.Schedule);

                // "Description"
                SetDescription(definition, record);

                // "Save"
                // Save location is handled by the recording process

                // "Advanced"
                SetAdvancedSettings(definition.Settings, record.AdvancedSettings, record.Schedule.Kind == RecordScheduleKind.RightNow);

                // Save xml data
                SaveXmlData(record);

                // Aditional task data
                SetAdditionalData(definition, record, _dbFile);

                // Action
                SetAction(definition, record, _dbFile, _logFolder);

                // Register task
                task = _taskFolder.RegisterTaskDefinition(_taskName, definition);
                isOk = true;

                // Run task right now?
                if (record.Schedule.Kind != RecordScheduleKind.RightNow)
                {
                    return(true);
                }

                try
                {
                    task.Run();
                    return(true);
                }
                catch (Exception ex)
                {
                    _exceptionHandler(new ExceptionEventData(Texts.TaskRunException, ex));
                    return(false);
                } // try-catch
            }
            catch (Exception ex)
            {
                _exceptionHandler(new ExceptionEventData(Texts.TaskCreationException, ex));
                return(false);
            }
            finally
            {
                if (!isOk)
                {
                    RecordTaskSerialization.TryDeleteFromDatabase(record.TaskId, _dbFile);
                } // if
                if (task != null)
                {
                    task.Dispose();
                    task = null;
                } // if
                if (definition != null)
                {
                    definition.Dispose();
                    definition = null;
                } // if
                if (_taskFolder != null)
                {
                    _taskFolder.Dispose();
                    _taskFolder = null;
                } // if
                if (taskScheduler != null)
                {
                    taskScheduler.Dispose();
                    taskScheduler = null;
                } // if
                _taskName = null;
            }     // try-finally
        }         // CreateTask
Esempio n. 23
0
        /// <summary>
        /// Creates the scheduler.
        /// </summary>
        /// <param name="schedulerData">The scheduler data.</param>
        /// <param name="showStatus">if set to <c>true</c> [status].</param>
        /// <returns></returns>
        private bool CreateScheduler(SchedulerModel schedulerData, bool showStatus)
        {
            bool result = false;

            try
            {
                using (var taskScheduler = new TaskService())
                {
                    TaskDefinition newTaskDefinition = taskScheduler.NewTask();
                    newTaskDefinition.RegistrationInfo.Author      = schedulerData.Author;
                    newTaskDefinition.RegistrationInfo.Description = schedulerData.Description;
                    newTaskDefinition.Settings.Compatibility       = TaskCompatibility.V2;

                    var action = (ExecAction)newTaskDefinition.Actions.AddNew(TaskActionType.Execute);
                    action.Id                             = schedulerData.Id;
                    action.Path                           = schedulerData.Path;
                    action.Arguments                      = schedulerData.Arguments;
                    action.WorkingDirectory               = schedulerData.WorkingDirectory;
                    newTaskDefinition.Principal.UserId    = Environment.UserName;
                    newTaskDefinition.Principal.LogonType = TaskLogonType.Password;

                    DailyTrigger trigger = newTaskDefinition.Triggers.AddNew(TaskTriggerType.Daily) as DailyTrigger;
                    if (trigger != null)
                    {
                        trigger.StartBoundary       = DateTime.Now.Date;
                        trigger.DaysInterval        = schedulerData.DaysInterval;
                        trigger.Repetition.Interval = schedulerData.RepetitionInterval;
                        trigger.Enabled             = true;
                    }

                    TaskFolder taskFolder = taskScheduler.GetFolder("\\");
                    CheckFolder(taskFolder);

                    if (string.IsNullOrEmpty(currentUserPassword))
                    {
                        var viewModel = new PasswordViewModel();
                        System.Windows.Window window = null;

                        if (System.Windows.Application.Current != null)
                        {
                            window = System.Windows.Application.Current.MainWindow;
                        }
                        if (window == null)
                        {
CheckPassword:
                            string password = null;
                            if (InputBox.Show("Authentication", string.Format(Constants.DefaultCulture, "Enter {0} Password:"******"UnableToCreateScheduler"), schedulerData.Description), Utilities.GetResourceValue("CaptionError"));
                            }
                            return(false);
                        }
                    }

                    taskFolder = taskScheduler.GetFolder("\\" + schedulerData.TaskFolder);
                    string userId = string.Concat(Environment.UserDomainName, "\\", Environment.UserName);
                    taskFolder.RegisterTaskDefinition(schedulerData.Id, newTaskDefinition, TaskCreation.CreateOrUpdate, userId, currentUserPassword, TaskLogonType.InteractiveTokenOrPassword);
                    result = true;
                    if (showStatus)
                    {
                        if (IsUiProcess)
                        {
                            NotificationHelper.ShowMessage(string.Format(CultureInfo.CurrentCulture, Utilities.GetResourceValue("SchedulerCreated"), schedulerData.Id), Utilities.GetResourceValue("CaptionInfo"));
                        }
                        SetFilePermission(schedulerData.Id);
                    }
                }
            }
            catch (Exception exception)
            {
                if (IsUiProcess)
                {
                    NotificationHelper.ShowMessage(string.Format(CultureInfo.CurrentCulture, Utilities.GetResourceValue("UnableToCreateScheduler"), schedulerData.Description, exception.Message), Utilities.GetResourceValue("CaptionError"));
                }
                else
                {
                    Logger.LogMessage(exception.Message, "CreateScheduler", LogType.Error, exception);
                }
            }
            return(result);
        }
        private void checkcollectorparams()
        {
            using (TaskService ts = new TaskService())
            {
                string execfolder = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
                string execname   = Path.Combine(execfolder, "WeatherCollector.exe");

                string schedulerfolder   = "YetAnotherPictureSlideshow";
                string schedulertaskname = "WeatherCollector";
                string taskname          = schedulerfolder + @"\" + schedulertaskname;

                bool    recreate = false;
                TS.Task t        = ts.GetTask(taskname);
                if (t != null)
                {
                    // check if existing task correspnds to current parameters
                    foreach (var action in t.Definition.Actions)
                    {
                        var eaction = action as ExecAction;
                        if (eaction == null)
                        {
                            continue;
                        }

                        if (eaction.Path == execname && eaction.WorkingDirectory == execfolder)
                        {
                            if (eaction.Arguments == _execparams)
                            {
                                continue;
                            }
                            if (string.IsNullOrEmpty(eaction.Arguments) && string.IsNullOrEmpty(_execparams))
                            {
                                continue;
                            }
                        }

                        try
                        {
                            //t.Definition.Actions.RemoveAt(0);

                            TaskFolder tf = ts.RootFolder.FindFolder(schedulerfolder);
                            tf.DeleteTask(schedulertaskname);
                            recreate = true;
                            break;
                        }
                        catch (Exception e)
                        {
                            string em = e.Message;
                        }
                    }
                }

                if (t == null || recreate)
                {
                    // Create a new task definition and assign properties
                    TaskDefinition td = ts.NewTask();
                    td.RegistrationInfo.Description = "Read weather info from web and store it into file";
                    td.Principal.LogonType          = TaskLogonType.InteractiveToken;
                    td.Settings.Enabled             = true;
                    td.Settings.ExecutionTimeLimit  = TimeSpan.FromMinutes(5);
                    td.Settings.Hidden = false;

                    td.Actions.Add(new ExecAction(execname, _execparams, execfolder));

                    // Add a trigger that will fire the task at this time every other day
                    DailyTrigger dt = (DailyTrigger)td.Triggers.Add(new DailyTrigger());
                    dt.StartBoundary       = DateTime.Now + TimeSpan.FromSeconds(10);
                    dt.RandomDelay         = TimeSpan.FromSeconds(60);
                    dt.EndBoundary         = DateTime.MaxValue;
                    dt.ExecutionTimeLimit  = TimeSpan.FromSeconds(90);
                    dt.Repetition.Duration = TimeSpan.FromHours(24);
                    dt.Repetition.Interval = TimeSpan.FromMinutes(15);

                    // Register the task in the folder
                    TaskFolder tf = ts.RootFolder.FindFolder(schedulerfolder);
                    if (tf == null)
                    {
                        tf = ts.RootFolder.CreateFolder(schedulerfolder, null, false);
                    }

                    tf.RegisterTaskDefinition(schedulertaskname, td);
                }

                _checkcollector = false;
            }
        }
Esempio n. 25
0
        public void addTask(string url, string tag, bool transcode, bool media, bool wake, bool edit)
        {
            //variable to check if this task is unique
            bool taskValid = true;

            //use tag as taskName
            string taskName = tag;

            //get directory that this application is executing in
            string currentPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            string batPath     = "\"" + currentPath + "\\bat\\genericStream.bat" + "\"";

            //build arguments string
            string taskArguments = url + " " + tag;

            if (transcode)
            {
                taskArguments += " " + "Y";
            }
            else
            {
                taskArguments += " " + "N";
            }
            if (media)
            {
                taskArguments += " " + "Y";
            }
            else
            {
                taskArguments += " " + "N";
            }

            //create new task
            using (TaskService ts = new TaskService())
            {
                TaskDefinition taskDefinition = ts.NewTask();
                taskDefinition.Actions.Add(new ExecAction(batPath, taskArguments, null));
                taskDefinition.Principal.RunLevel = TaskRunLevel.Highest;

                //set task wake condition based on bool wake
                taskDefinition.Settings.WakeToRun = wake;

                //check if this taskName already exists in StreamDVR folder
                TaskFolder myFolder = ts.RootFolder.SubFolders["StreamDVR"];
                foreach (Microsoft.Win32.TaskScheduler.Task allTasks in myFolder.AllTasks)
                {
                    if (allTasks.Name == taskName)
                    {
                        taskValid = false;
                        if (edit == false)
                        {
                            //task already exists and edit flag is set to false
                            DialogResult dialogResult = MessageBox.Show("That tag already exists. Tag must be unique", "Error", MessageBoxButtons.OK);
                            // Create a new instance of the Form2 class
                            Form2 settingsForm = new Form2(url, tag, transcode, media, wake);

                            // Show the settings form
                            settingsForm.ShowDialog();
                            if (settingsForm.DialogResult != DialogResult.Cancel)
                            {
                                addTask(settingsForm.form2StreamUrl, settingsForm.form2StreamTag, settingsForm.form2StreamTranscode, settingsForm.form2StreamMedia, settingsForm.form2StreamWake, false);
                            }
                        }
                        else
                        {
                            //task already exists and edit flag is set to true
                            allTasks.Definition.Actions.Clear();
                            allTasks.Definition.Actions.Add(new ExecAction(batPath, taskArguments, null));
                            allTasks.Definition.Settings.WakeToRun = wake;
                            allTasks.RegisterChanges();
                        }
                    }
                }

                if (taskValid == true)
                {
                    //task does not already exist. create

                    myFolder.RegisterTaskDefinition(taskName, taskDefinition);
                    //open trigger editor for new task
                    openTriggerEditor(taskName, null);
                    loadTasks(taskName);
                }
            }
        }
Esempio n. 26
0
        /// <inheritdoc cref="DeployerInterface"/>
        public void deploy()
        {
            var settings = this.Settings;

            string cronId = this.Deployment.shortid + "_" + settings.id;

            string pwfile = UtilsSystem.CombinePaths(this.Deployment.runtimePath, "cronjobs_" + settings.id + ".ps1");

            // Necesitamos un Bat que llame al powershel, este siempre tiene el mismo aspecto.
            string batfile = UtilsSystem.CombinePaths(this.Deployment.runtimePath, "cronjobs_" + settings.id + ".bat");

            Encoding enc = Encoding.GetEncoding("Windows-1252");

            File.WriteAllText(batfile, "powershell " + pwfile, enc);

            StringBuilder command = new StringBuilder();

            // Add path to environment.
            command.AppendLine(
                $"$env:Path = \"{UtilsSystem.CombinePaths(this.Deployment.runtimePath, "include_path")};\" + $env:Path");

            // Move to runtime.
            command.AppendLine($"cd \"{UtilsSystem.CombinePaths(this.Deployment.appPath)}\"");

            // Add path of project to the enviroment
            command.AppendLine($"$env:AppPath = \"{UtilsSystem.CombinePaths(this.Deployment.appPath)}\"");

            // Whatever deployers wanna do...
            var logger    = new logger.NullLogger();
            var deployers = this.Deployment.GrabDeployers(logger);

            foreach (var deployer in deployers)
            {
                deployer.deployConsoleEnvironment(command);
            }

            // Drop the user commands
            if (!string.IsNullOrWhiteSpace(settings.command))
            {
                command.AppendLine(settings.command);
            }

            if (settings.commands != null)
            {
                foreach (var cmd in settings.commands)
                {
                    command.AppendLine(cmd);
                }
            }

            File.WriteAllText(pwfile, command.ToString());

            // Nuestro scheduler tiene un nombre
            // definido.
            using (TaskService ts = new TaskService())
            {
                // Create a new task definition and assign properties
                TaskDefinition td = ts.NewTask();

                // Run with highest level to avoid UAC issues
                // https://www.devopsonwindows.com/create-scheduled-task/
                td.Principal.RunLevel = TaskRunLevel.Highest;

                string password = settings.taskUserPassword;

                if (settings.taskLogonType.HasValue)
                {
                    td.Principal.LogonType = (TaskLogonType)settings.taskLogonType.Value;
                }

                if (settings.taskUserId == "auto")
                {
                    td.Principal.UserId    = this.Deployment.WindowsUsernameFqdn();
                    td.Principal.LogonType = TaskLogonType.Password;
                    password = this.Deployment.GetWindowsPassword();

                    // Make sure that the user has the LogonAsBatchRight
                    UtilsWindowsAccounts.SetRight(this.Deployment.WindowsUsernameFqdn(), "SeBatchLogonRight", logger);
                }

                // Default to the SYSTEM account.
                else if (string.IsNullOrWhiteSpace(settings.taskUserId))
                {
                    td.Principal.UserId    = "SYSTEM";
                    td.Principal.LogonType = TaskLogonType.ServiceAccount;
                    password = null;
                }

                td.RegistrationInfo.Description = cronId;

                // Create a trigger that will fire the task every 5 minutes.
                var trigger = new DailyTrigger();

                // Habilitada...
                trigger.Enabled = true;

                // Repetir cada 24 horas.
                trigger.DaysInterval = 1;

                // Repetir durante 24 horas en la frecuencia establecida.
                trigger.Repetition = new RepetitionPattern(new TimeSpan(0, settings.frequency, 0), new TimeSpan(24, 0, 0), true);

                // Para que arranque dos minutos después del deploy.
                trigger.StartBoundary = DateTime.Now.AddMinutes(2);

                // Enablin/disabling will happen during start/stop of service
                td.Settings.Enabled = false;

                // Un solo trigger.
                td.Triggers.Add(trigger);

                // Create an action that will launch the bat launcher.
                td.Actions.Add(new ExecAction(batfile, null, null));

                TaskFolder f = this.GetFolder(ts);

                // Register the task in the root folder
                if (!string.IsNullOrWhiteSpace(password) && td.Principal.LogonType == TaskLogonType.Password)
                {
                    f.RegisterTaskDefinition(td.RegistrationInfo.Description, td, TaskCreation.Create, td.Principal.UserId, this.Deployment.GetWindowsPassword(), td.Principal.LogonType);
                }
                else
                {
                    f.RegisterTaskDefinition(td.RegistrationInfo.Description, td, TaskCreation.Create, td.Principal.UserId);
                }
            }
        }
        internal static void LongTest(TaskService ts, System.IO.TextWriter output, params string[] arg)
        {
            string user = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

            Version ver   = ts.HighestSupportedVersion;
            bool    isV12 = (ver >= new Version(1, 2));
            bool    isV13 = (ver >= new Version(1, 3));
            bool    isV14 = (ver >= new Version(1, 4));

            output.WriteLine("Highest version: " + ver);
            output.WriteLine("Server: {0} ({1}); User: {2}\\{3}", ts.TargetServer, ts.Connected ? "Connected" : "Disconnected", ts.UserAccountDomain, ts.UserName);

            output.WriteLine("Running tasks:");
            foreach (RunningTask rt in ts.GetRunningTasks(true))
            {
                if (rt != null)
                {
                    output.WriteLine("+ {0}, {1} ({2})", rt.Name, rt.Path, rt.State);
                    if (ver.Minor > 0)
                    {
                        output.WriteLine("  Current Action: " + rt.CurrentAction);
                    }
                }
            }

            string         filter = arg.Length > 0 ? arg[0] : string.Empty;
            TaskFolder     tf     = ts.RootFolder;
            TaskCollection tasks  = tf.GetTasks(new Wildcard(filter));

            output.WriteLine("\nRoot folder tasks matching \"{1}\" ({0}):", tasks.Count, filter);
            foreach (Task t in tasks)
            {
                try
                {
                    output.WriteLine("+ {0}, {1} ({2}) - {3}", t.Name, t.Definition.RegistrationInfo.Author, t.State, t.Definition.Settings.Compatibility);
                    foreach (Trigger trg in t.Definition.Triggers)
                    {
                        output.WriteLine(" + {0}", trg);
                    }
                    foreach (var act in t.Definition.Actions)
                    {
                        output.WriteLine(" = {0}", act);
                    }
                }
                catch { }
            }

            output.WriteLine("\n***Finding defrag task***");
            Task ft = ts.FindTask("*defrag*");

            if (ft != null)
            {
                output.WriteLine("Defrag task found at " + ft.Path);
            }
            else
            {
                output.WriteLine("Defrag task not found.");
            }

            TaskFolderCollection tfs = tf.SubFolders;

            if (tfs.Count > 0)
            {
                output.WriteLine("\nSub folders:");
                try
                {
                    foreach (TaskFolder sf in tfs)
                    {
                        output.WriteLine("+ {0}", sf.Path);
                    }
                }
                catch (Exception ex)
                {
                    output.WriteLine(ex.ToString());
                }
            }

            if (isV12)
            {
                output.WriteLine("\n***Checking folder retrieval***");
                try
                {
                    const string testFolder = "David's TestFolder";
                    try { tf.CreateFolder(testFolder); }
                    catch (System.Runtime.InteropServices.COMException cex) { if (cex.ErrorCode != -2147024713)
                                                                              {
                                                                                  throw;
                                                                              }
                    }
                    catch { throw; }
                    TaskFolder sub = tf.SubFolders[testFolder];
                    output.WriteLine("\nSubfolder path: " + sub.Path);
                    try
                    {
                        ts.AddTask(testFolder + @"\MyTask", new DailyTrigger(), new ExecAction("notepad"));
                        output.WriteLine(" - Tasks: " + sub.Tasks.Count.ToString());
                        sub.DeleteTask("MyTask");
                    }
                    catch (Exception ex)
                    {
                        output.WriteLine(ex.ToString());
                    }
                    tf.DeleteFolder(testFolder);
                }
                catch (NotSupportedException) { }
                catch (Exception ex)
                {
                    output.WriteLine(ex.ToString());
                }
            }

            output.WriteLine("\n***Checking task creation***");
            try
            {
                TaskDefinition td = ts.NewTask();
                td.Data = "Your data";
                //td.Principal.UserId = "SYSTEM";
                //td.Principal.LogonType = TaskLogonType.ServiceAccount;
                if (isV12)
                {
                    td.Principal.LogonType = TaskLogonType.S4U;
                }
                td.RegistrationInfo.Author             = "dahall";
                td.RegistrationInfo.Description        = "Does something";
                td.RegistrationInfo.Documentation      = "Don't pretend this is real.";
                td.Settings.DisallowStartIfOnBatteries = true;
                td.Settings.Enabled                    = false;
                td.Settings.ExecutionTimeLimit         = TimeSpan.Zero;         // FromHours(2);
                td.Settings.Hidden                     = false;
                td.Settings.IdleSettings.IdleDuration  = TimeSpan.FromMinutes(20);
                td.Settings.IdleSettings.RestartOnIdle = false;
                td.Settings.IdleSettings.StopOnIdleEnd = false;
                td.Settings.IdleSettings.WaitTimeout   = TimeSpan.FromMinutes(10);
                td.Settings.Priority                   = System.Diagnostics.ProcessPriorityClass.Normal;
                td.Settings.RunOnlyIfIdle              = true;
                td.Settings.RunOnlyIfNetworkAvailable  = true;
                td.Settings.StopIfGoingOnBatteries     = true;
                if (isV12)
                {
                    td.Principal.RunLevel = TaskRunLevel.Highest;                     //.LUA;
                    td.Principal.Id       = "Author";
                    td.RegistrationInfo.SecurityDescriptorSddlForm = "D:P(A;;FA;;;BA)(A;;FA;;;SY)(A;;FRFX;;;LS)";
                    td.RegistrationInfo.Source  = "Test App";
                    td.RegistrationInfo.URI     = "test://app";
                    td.RegistrationInfo.Version = new Version(0, 9);
                    //td.Settings.AllowDemandStart = false;
                    td.Settings.AllowHardTerminate     = false;
                    td.Settings.Compatibility          = TaskCompatibility.V2;
                    td.Settings.DeleteExpiredTaskAfter = TimeSpan.FromMinutes(1);
                    td.Settings.MultipleInstances      = TaskInstancesPolicy.StopExisting;
                    td.Settings.StartWhenAvailable     = true;
                    td.Settings.WakeToRun       = true;
                    td.Settings.RestartCount    = 5;
                    td.Settings.RestartInterval = TimeSpan.FromSeconds(100);
                    //td.Settings.NetworkSettings.Id = new Guid("{99AF272D-BC5B-4F64-A5B7-8688392C13E6}");
                }
                if (isV13)
                {
                    td.Settings.Compatibility = TaskCompatibility.V2_1;
                    td.Settings.DisallowStartOnRemoteAppSession = true;
                    td.Settings.UseUnifiedSchedulingEngine      = false;

                    /*td.Principal.ProcessTokenSidType = TaskProcessTokenSidType.Unrestricted;
                     * td.Principal.RequiredPrivileges.Add(TaskPrincipalPrivilege.SeBackupPrivilege);
                     * td.Principal.RequiredPrivileges.Add(TaskPrincipalPrivilege.SeDebugPrivilege);
                     * td.Principal.RequiredPrivileges.Add(TaskPrincipalPrivilege.SeImpersonatePrivilege);
                     * output.Write("Priv: ");
                     * //output.Write(td.Principal.RequiredPrivileges[0]);
                     * foreach (TaskPrincipalPrivilege item in td.Principal.RequiredPrivileges)
                     *      output.Write(item.ToString() + ", ");
                     * output.WriteLine();*/
                }
                if (isV14)
                {
                    td.Settings.Compatibility = TaskCompatibility.V2_2;
                    td.Settings.Volatile      = true;
                    if (td.Principal.LogonType == TaskLogonType.ServiceAccount)
                    {
                        td.Settings.MaintenanceSettings.Exclusive = true;
                        td.Settings.MaintenanceSettings.Period    = TimeSpan.FromDays(5);
                        td.Settings.MaintenanceSettings.Deadline  = TimeSpan.FromDays(15);
                    }
                }

                // Setup Triggers
                if (isV12)
                {
                    BootTrigger bTrigger = (BootTrigger)td.Triggers.Add(new BootTrigger {
                        Enabled = false
                    });                                                                                                           //(BootTrigger)td.Triggers.AddNew(TaskTriggerType.Boot);
                    if (isV12)
                    {
                        bTrigger.Delay = TimeSpan.FromMinutes(5);
                    }
                }

                DailyTrigger dTrigger = (DailyTrigger)td.Triggers.Add(new DailyTrigger {
                    DaysInterval = 2
                });
                if (isV12)
                {
                    dTrigger.RandomDelay = TimeSpan.FromHours(2);
                }

                if (isV12)
                {
                    EventTrigger eTrigger = (EventTrigger)td.Triggers.Add(new EventTrigger());
                    eTrigger.Subscription = "<QueryList><Query Id=\"0\" Path=\"Security\"><Select Path=\"Security\">*[System[Provider[@Name='VSSAudit'] and EventID=25]]</Select></Query></QueryList>";
                    eTrigger.ValueQueries.Add("Name", "Value");

                    td.Triggers.Add(new RegistrationTrigger {
                        Delay = TimeSpan.FromMinutes(5)
                    });

                    td.Triggers.Add(new SessionStateChangeTrigger {
                        StateChange = TaskSessionStateChangeType.ConsoleConnect, UserId = user
                    });
                    td.Triggers.Add(new SessionStateChangeTrigger {
                        StateChange = TaskSessionStateChangeType.ConsoleDisconnect
                    });
                    td.Triggers.Add(new SessionStateChangeTrigger {
                        StateChange = TaskSessionStateChangeType.RemoteConnect
                    });
                    td.Triggers.Add(new SessionStateChangeTrigger {
                        StateChange = TaskSessionStateChangeType.RemoteDisconnect
                    });
                    td.Triggers.Add(new SessionStateChangeTrigger {
                        StateChange = TaskSessionStateChangeType.SessionLock, UserId = user
                    });
                    td.Triggers.Add(new SessionStateChangeTrigger {
                        StateChange = TaskSessionStateChangeType.SessionUnlock
                    });
                }

                td.Triggers.Add(new IdleTrigger());

                LogonTrigger lTrigger = (LogonTrigger)td.Triggers.Add(new LogonTrigger());
                if (isV12)
                {
                    lTrigger.Delay  = TimeSpan.FromMinutes(15);
                    lTrigger.UserId = user;
                    lTrigger.Repetition.Interval = TimeSpan.FromSeconds(1000);
                }

                MonthlyTrigger mTrigger = (MonthlyTrigger)td.Triggers.Add(new MonthlyTrigger());
                mTrigger.DaysOfMonth  = new int[] { 3, 6, 10, 18 };
                mTrigger.MonthsOfYear = MonthsOfTheYear.July | MonthsOfTheYear.November;
                if (isV12)
                {
                    mTrigger.RunOnLastDayOfMonth = true;
                }
                mTrigger.EndBoundary = DateTime.Today + TimeSpan.FromDays(90);

                MonthlyDOWTrigger mdTrigger = (MonthlyDOWTrigger)td.Triggers.Add(new MonthlyDOWTrigger());
                mdTrigger.DaysOfWeek   = DaysOfTheWeek.AllDays;
                mdTrigger.MonthsOfYear = MonthsOfTheYear.January | MonthsOfTheYear.December;
                if (isV12)
                {
                    mdTrigger.RunOnLastWeekOfMonth = true;
                }
                mdTrigger.WeeksOfMonth = WhichWeek.FirstWeek;

                TimeTrigger tTrigger = (TimeTrigger)td.Triggers.Add(new TimeTrigger());
                tTrigger.StartBoundary = DateTime.Now + TimeSpan.FromMinutes(1);
                tTrigger.EndBoundary   = DateTime.Today + TimeSpan.FromDays(7);
                if (isV12)
                {
                    tTrigger.ExecutionTimeLimit = TimeSpan.FromSeconds(19);
                }
                if (isV12)
                {
                    tTrigger.Id = "Time test";
                }
                tTrigger.Repetition.Duration          = TimeSpan.FromMinutes(21);
                tTrigger.Repetition.Interval          = TimeSpan.FromMinutes(17);
                tTrigger.Repetition.StopAtDurationEnd = true;

                WeeklyTrigger wTrigger = (WeeklyTrigger)td.Triggers.Add(new WeeklyTrigger());
                wTrigger.DaysOfWeek    = DaysOfTheWeek.Monday;
                wTrigger.WeeksInterval = 3;

                // Setup Actions
                td.Actions.Add(new ExecAction("notepad.exe", "c:\\test.log", null));
                if (isV12)
                {
                    td.Actions.Context = "Author";
                    if (td.Principal.LogonType == TaskLogonType.InteractiveToken || td.Principal.LogonType == TaskLogonType.Group || td.Principal.LogonType == TaskLogonType.S4U)
                    {
                        td.Actions.Add(new ShowMessageAction("Running Notepad", "Info"));
                    }
                    td.Actions.Add(new EmailAction("Testing", "*****@*****.**", "*****@*****.**", "You've got mail.", "mail.myisp.com")
                    {
                        Id = "Email", Attachments = new object[] { (string)new TemporaryScopedFile() }
                    });
                    var email = (EmailAction)td.Actions["Email"];
                    email.HeaderFields.Add("Precedence", "bulk");
                    td.Actions.Add(new ComHandlerAction(new Guid("{BF300543-7BA5-4C17-A318-9BBDB7429A21}"), @"C:\Users\dahall\Documents\Visual Studio 2010\Projects\TaskHandlerProxy\TaskHandlerSample\bin\Release\TaskHandlerSample.dll|TaskHandlerSample.TaskHandler|MoreData"));
                }

                // Validate and Register task
                WriteXml(td, "PreRegTest");
                td.Validate(true);
                Task t = tf.RegisterTaskDefinition("Test", td);
                WriteXml(t);

                // Try copying it
                TaskDefinition td2 = ts.NewTask();
                foreach (Trigger tg in td.Triggers)
                {
                    td2.Triggers.Add((Trigger)tg.Clone());
                }
                foreach (Microsoft.Win32.TaskScheduler.Action a in td.Actions)
                {
                    td2.Actions.Add((Microsoft.Win32.TaskScheduler.Action)a.Clone());
                }
                tf.RegisterTaskDefinition("Test2", td2, TaskCreation.CreateOrUpdate, user, null, TaskLogonType.InteractiveToken, null);
                tf.DeleteTask("Test2");
            }
            catch (Exception ex)
            {
                output.WriteLine(ex.ToString());
                return;
            }

            // Display results
            Task runningTask = tf.Tasks["Test"];

            output.WriteLine("\nNew task will next run at " + runningTask.NextRunTime);
            DateTime[] times = runningTask.GetRunTimes(DateTime.Now, DateTime.Now + TimeSpan.FromDays(7), 0);
            if (times.Length > 0)
            {
                output.WriteLine("\nNew task will run at the following times over the next week:");
                foreach (DateTime dt in times)
                {
                    output.WriteLine("  {0}", dt);
                }
            }
            output.WriteLine("\nNew task triggers:");
            for (int i = 0; i < runningTask.Definition.Triggers.Count; i++)
            {
                output.WriteLine("  {0}: {1}", i, runningTask.Definition.Triggers[i]);
            }
            output.WriteLine("\nNew task actions:");
            for (int i = 0; i < runningTask.Definition.Actions.Count; i++)
            {
                output.WriteLine("  {0}: {1}", i, runningTask.Definition.Actions[i]);
            }

            // Loop through event logs for this task and find action completed events newest to oldest
            if (isV12)
            {
                output.WriteLine("\nTask history enumeration:");
                TaskEventLog log = new TaskEventLog(@"\Maint", new int[] { 201 }, DateTime.Now.AddDays(-7))
                {
                    EnumerateInReverse = false
                };
                foreach (TaskEvent ev in log)
                {
                    output.WriteLine("  Completed action '{0}' ({2}) at {1}.", ev.GetDataValue("ActionName"), ev.TimeCreated.Value, ev.GetDataValue("ResultCode"));
                }
            }

            DisplayTask(runningTask, true);
            tf.DeleteTask("Test");
        }
Esempio n. 28
0
        public void SetMyHutTask(DateTime startDate)
        {
            utils.Log(NLog.LogLevel.Debug, string.Format("Schedule next task {0} at {1}", TaskName, startDate.ToString("yyyy-MM-dd HH:mm")));

            TaskService ts = new TaskService();
            TaskFolder  tf = ts.GetFolder(TaskFolder);

            if (tf == null)
            {
                tf = ts.RootFolder.CreateFolder(TaskFolder);
            }

            Task task = GetTask();

            TaskDefinition def = null;

            if (task == null)
            {
                utils.Log(NLog.LogLevel.Warn, string.Format("Crie uma task com o nome '{0}' na pasta '{1}' no Task Scheduler.", TaskName, TaskFolder));
                def = ts.NewTask();
            }
            else
            {
                def = task.Definition;
            }

            try
            {
                DeleteTriggers(def);
                DeleteActions(def);

                ExecAction action = new ExecAction();
                action.Path             = Assembly.GetExecutingAssembly().Location;
                action.Arguments        = ConfigFile;
                action.WorkingDirectory = Directory;
                def.Actions.Add(action);

                TimeTrigger trigger = new TimeTrigger(startDate);
                trigger.Enabled = true;
                def.Triggers.Add(trigger);

                def.Principal.LogonType = TaskLogonType.ServiceAccount;
                def.Principal.UserId    = "SYSTEM";
                def.Principal.RunLevel  = TaskRunLevel.LUA;

                def.Settings.DisallowStartIfOnBatteries = true;
                def.Settings.StopIfGoingOnBatteries     = true;
                def.Settings.AllowHardTerminate         = true;
                def.Settings.StartWhenAvailable         = false;
                def.Settings.RunOnlyIfNetworkAvailable  = false;
                def.Settings.IdleSettings.StopOnIdleEnd = true;
                def.Settings.IdleSettings.RestartOnIdle = false;
                def.Settings.AllowDemandStart           = true;
                def.Settings.Enabled       = true;
                def.Settings.Hidden        = false;
                def.Settings.RunOnlyIfIdle = false;
                def.Settings.WakeToRun     = true;

                // Este ação requere direitos de Administrador. Executar a aplicação com "Run as Administrator".
                tf.RegisterTaskDefinition(TaskName, def);
            }
            catch (Exception ex)
            {
                utils.Log(NLog.LogLevel.Error, string.Format("ERROR scheduling next MyHut Task {0} - {1}", def.XmlText, ex.Message));
                throw (ex);
            }
        }