Ejemplo n.º 1
1
        private void StartNew(DateTime startTime, string action, string parameters, string taskName)
        {
            using (TaskService ts = new TaskService())
            {
                TaskDefinition td = ts.NewTask();
                td.Principal.RunLevel = TaskRunLevel.Highest;
                td.RegistrationInfo.Description = "instaprinter";

                td.Triggers.Add(new TimeTrigger(startTime));
                td.Actions.Add(new ExecAction(action, parameters));

                // Retrieve the task, change the trigger and re-register it
                Task t = ts.GetTask(taskName);
                if (t != null)
                {
                    td = t.Definition;
                    td.Triggers[0].StartBoundary = startTime;

                    ts.RootFolder.RegisterTaskDefinition(taskName, td);
                }
                else
                {
                    ts.RootFolder.RegisterTaskDefinition(taskName, td);
                }
            }
        }
Ejemplo n.º 2
1
        public void AddTask(int min, int hour, bool restart)
        {
            var taskService = new TaskService();

            //Create task definition
            var taskDefinition = taskService.NewTask();
            taskDefinition.RegistrationInfo.Description = min + "@" + hour + "@" + ((restart) ? "r" : "s");
            taskDefinition.Principal.UserId = "SYSTEM";

            var trigger = new DailyTrigger
            {
                StartBoundary = DateTime.Today + TimeSpan.FromHours(hour) + TimeSpan.FromMinutes(min)
            };

            taskDefinition.Triggers.Add(trigger);

            //Create task action
            var fileName = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + @"Power.exe");

            taskDefinition.Actions.Add(restart
                ? new ExecAction(fileName, "reboot \"This computer is going to reboot.\"")
                : new ExecAction(fileName, "shutdown \"This computer is going to shutdown to save power.\""));

            taskDefinition.Settings.AllowDemandStart = false;
            taskDefinition.Settings.DisallowStartIfOnBatteries = false;
            taskDefinition.Settings.DisallowStartOnRemoteAppSession = false;
            taskDefinition.Settings.StopIfGoingOnBatteries = false;

            taskService.RootFolder.RegisterTaskDefinition(@"FOG\" + taskDefinition.RegistrationInfo.Description,
                taskDefinition);
            taskService.Dispose();
        }
 internal static void FindTask(TaskService ts, System.IO.TextWriter output, params string[] arg)
 {
     try
     {
         Task t = ts.FindTask(arg[0]);
         if (t == null)
             output.WriteLine(string.Format("Task '{0}' not found.", arg[0]));
         else
         {
             output.WriteLine(string.Format("Task '{0}' found. Created on {1:g} and last run on {2:g}.", t.Name, t.Definition.RegistrationInfo.Date, t.LastRunTime));
             if (t.Definition.Triggers.ContainsType(typeof(CustomTrigger)))
             {
                 foreach (var tr in t.Definition.Triggers)
                 {
                     CustomTrigger ct = tr as CustomTrigger;
                     if (ct != null && ct.Properties.Count > 0)
                     {
                         output.WriteLine("Custom Trigger Properties:");
                         int i = 0;
                         foreach (var name in ct.Properties.Names)
                             output.WriteLine("{0}. {1} = {2}", ++i, name, ct.Properties[name]);
                     }
                 }
             }
         }
     }
     catch (Exception ex)
     {
         output.WriteLine(ex.ToString());
     }
 }
Ejemplo n.º 4
1
 public static void AddStores2TaskScheduler(string strStoresPath, string strActionPath)
 {
     string[] strXMLFiles = Directory.GetFiles(strStoresPath, "*.xml");
     TaskService ts = new TaskService();
     Console.ForegroundColor = ConsoleColor.Cyan;
     Console.WriteLine("");
     Console.WriteLine("Adding stores to the Task Scheduler");
     Console.ForegroundColor = ConsoleColor.Green;
     foreach (string strXMLFile in strXMLFiles)
     {
         string storeName = Path.GetFileName(strXMLFile);
         string taskName = @"BC Store " + storeName;
         Task t = ts.FindTask(taskName);
         if (t == null)
         {
             Console.WriteLine("  + " + storeName);
             DailyTrigger dt = new DailyTrigger();
             dt.StartBoundary = DateTime.Today.Date;
             dt.Repetition.Duration = TimeSpan.FromMinutes(1430);
             dt.Repetition.Interval = TimeSpan.FromMinutes(2);
             ts.AddTask(taskName, dt, new ExecAction(strActionPath, strXMLFile, null));
             Thread.Sleep(500);
         }
     }
     Console.ForegroundColor = ConsoleColor.Cyan;
     Console.WriteLine("All stores added");
     Console.WriteLine("");
     Console.WriteLine("");
     Console.ForegroundColor = ConsoleColor.White;
 }
Ejemplo n.º 5
1
 public static bool IsAutostart()
 {
     using (TaskService ts = new TaskService())
     {
         Microsoft.Win32.TaskScheduler.Task task = ts.GetTask("Touchmote");
         return task != null;
     }
 }
Ejemplo n.º 6
1
 public void DeleteTask(string name)
 {
     using (TaskService ts = new TaskService())
     {
         if (ts.GetTask(name) != null)
         {
             ts.RootFolder.DeleteTask(name);
         }
     }
 }
Ejemplo n.º 7
1
 public static void modifyTask(DailyTrigger dt)
 {
     using (TaskService ts = new TaskService())
     {
         Task t = ts.GetTask("taxiService");
        TaskDefinition td = t.Definition;
        td.Triggers.Add(dt);
        ts.RootFolder.RegisterTaskDefinition(@"taxiService", td);
     }
 }
Ejemplo n.º 8
1
 public static void RunTask()
 {
     using (TaskService ts = new TaskService())
     {
         Task t = ts.GetTask("CudaAdministratorSkipUAC");
         if (t != null)
         {
             t.Run();
         }
     }
 }
Ejemplo n.º 9
0
        public void CreateTask(TaskService service)
        {
            var path = Application.StartupPath;

            try
            {
                var task = service.AddTask("SP_Field_Monitor",
                                           new DailyTrigger() { StartBoundary = DateTime.Parse("10:00:00 AM") },
                                           new ExecAction(path + "\\SPFieldMonitor.exe",
                                                          "-user [email protected] -password \"!thisisatestitisonlyatest!\"",
                                                          path), "SYSTEM");

                var trigger = new DailyTrigger() { StartBoundary = DateTime.Parse("11:00:00 AM") };
                trigger.Repetition.Duration = TimeSpan.FromHours(22);
                trigger.Repetition.Interval = TimeSpan.FromHours(1);

                var checkTask = service.AddTask("SP_Field_Monitor_Check", trigger,
                                           new ExecAction(path + "\\SPFieldMonitor.exe",
                                                          "-user [email protected] -password \"!thisisatestitisonlyatest!\" -check",
                                                          path), "SYSTEM");

                MessageBox.Show(
                    "The daily task has been scheduled.\nIf you move any of the Field Monitor executables, you will need to click this button again to reschedule the task.",
                    "Success!", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
            catch (UnauthorizedAccessException)
            {
                MessageBox.Show(
                    "You need administrator privileges to schedule this task. Try running the program as an administrator.",
                    "Insufficient Access Rights", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Ejemplo n.º 10
0
        public void Install(IEnumerable<RepetitiveTask> tasks)
        {
            tasks = tasks.ToList();

            using (var ts = new TaskService())
            {
                var path = Assembly.GetEntryAssembly().Location;

                foreach (var t in tasks)
                {
                    var definition = ts.NewTask();
                    definition.Settings.Enabled = true;
                    definition.RegistrationInfo.Description = t.Description;

                    AddTrigger(definition, t);

                    definition.Actions.Add(new ExecAction(t.Path ?? path, t.Parameters, Path.GetDirectoryName(path)));

                    ts.RootFolder.RegisterTaskDefinition(
                        t.Name,
                        definition,
                        TaskCreation.CreateOrUpdate,
                        "SYSTEM",
                        null,
                        TaskLogonType.ServiceAccount);

                    OnTaskInstalledEvent(new TaskEventArgs { Task = t });
                }
            }
        }
		/// <summary>
		/// Initializes a new instance of the <see cref="TaskEditDialog"/> class.
		/// </summary>
		/// <param name="service">A <see cref="TaskService"/> instance.</param>
		/// <param name="td">An optional <see cref="TaskDefinition"/>. Leaving null creates a new task.</param>
		/// <param name="editable">If set to <c>true</c> the task will be editable in the dialog.</param>
		/// <param name="registerOnAccept">If set to <c>true</c> the task will be registered when Ok is pressed.</param>
		public TaskEditDialog(TaskService service, TaskDefinition td = null, bool editable = true, bool registerOnAccept = true)
		{
			InitializeComponent();
			this.Editable = editable;
			this.Initialize(service, td);
			this.RegisterTaskOnAccept = registerOnAccept;
		}
Ejemplo n.º 12
0
 public void RemoveTask(int min, int hour, bool restart)
 {
     var taskService = new TaskService();
     var task = min + "@" + hour + "@" + ((restart) ? "r" : "s");
     taskService.RootFolder.DeleteTask(@"FOG\" + task);
     taskService.Dispose();
 }
Ejemplo n.º 13
0
        /// <summary>
        /// Creates default task in the Task Scheduler service
        /// </summary>
        /// <param name="taskName">task name</param>
        /// <param name="isEnabled">true - if enabled, false - otherwise</param>
        public static void CreateDefaultTask(string taskName, bool isEnabled)
        {
            try
            {
                DeleteTask(taskName);

                TaskService service = new TaskService();
                TaskDefinition td = service.NewTask();

                td.Settings.Enabled = isEnabled;
                td.RegistrationInfo.Description = "Free Driver Scout";
                td.Principal.RunLevel = TaskRunLevel.Highest;

                // Create an action that will launch Notepad whenever the trigger fires
                td.Actions.Add(new ExecAction(Environment.CurrentDirectory + "\\1Click.exe", null, Environment.CurrentDirectory));

                WeeklyTrigger mTrigger = new WeeklyTrigger();
                mTrigger.DaysOfWeek = DaysOfTheWeek.Friday;
                mTrigger.StartBoundary = DateTime.Today.AddHours(12);

                mTrigger.Repetition.StopAtDurationEnd = false;
                td.Triggers.Add(mTrigger);
                // Register the task in the root folder
                service.RootFolder.RegisterTaskDefinition(taskName, td);

            }
            catch { }
        }
Ejemplo n.º 14
0
 public static void DisableStartupTask()
 {
     using (TaskService _taskService = new TaskService())
     {
         _taskService.RootFolder.DeleteTask(_taskName, false);
     }
 }
Ejemplo n.º 15
0
 public void TaskShedulerWrapper_Dev2TaskSettings_PassThrough()
 {
     var service = new TaskService();
     var task =service.NewTask();
     var settings = new Dev2TaskSettings(task.Settings);
     settings.AllowDemandStart = true;
     settings.DeleteExpiredTaskAfter = new TimeSpan(2);
     settings.AllowHardTerminate = true;
     settings.DisallowStartOnRemoteAppSession = true;
     settings.Enabled = false;
     settings.ExecutionTimeLimit = new TimeSpan(3);
     settings.Hidden = true;
     settings.MultipleInstances = TaskInstancesPolicy.IgnoreNew;
     settings.Priority = ProcessPriorityClass.High;
     settings.RestartCount = 3;
     settings.StartWhenAvailable = false;
     settings.WakeToRun = true;
     var native = task.Settings;
     Assert.AreEqual(settings.AllowDemandStart,native.AllowDemandStart);
     Assert.AreEqual(settings.AllowHardTerminate,native.AllowHardTerminate);
     Assert.AreEqual(settings.DeleteExpiredTaskAfter,native.DeleteExpiredTaskAfter);
     Assert.AreEqual(settings.DisallowStartOnRemoteAppSession,native.DisallowStartIfOnBatteries);
     Assert.AreEqual(settings.Enabled,settings.Enabled);
     Assert.AreEqual(settings.ExecutionTimeLimit,native.ExecutionTimeLimit);
     Assert.AreEqual(settings.ExecutionTimeLimit,native.ExecutionTimeLimit);
     Assert.AreEqual(settings.Hidden,native.Hidden);
     Assert.AreEqual(settings.MultipleInstances,native.MultipleInstances);
     Assert.AreEqual(settings.RestartCount,native.RestartCount);
     Assert.AreEqual(settings.Priority,native.Priority);
     Assert.AreEqual(settings.RestartInterval,native.RestartInterval);
     Assert.AreEqual(settings.StartWhenAvailable,native.StartWhenAvailable);
     Assert.AreEqual(settings.WakeToRun,native.WakeToRun);
 }
Ejemplo n.º 16
0
 public void clearSchedules()
 {
     string strTaskID = "";
     try
     {
         // Get the service on the local machine
         TaskService ts = new TaskService();
         // Delete Schedules
         DataTable dt = this.GetSchedules(1);
         foreach (DataRow dr in dt.Rows)
         {
             strTaskID = dr["TaskID"].ToString();
             if (ts.FindTask(strTaskID, true) != null)
             {
                 // Remove the task we just created
                 ts.RootFolder.DeleteTask(strTaskID);
             }
             // Delete schedules follow taskid
             this.DeleleSchedules(strTaskID);
         }
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Ejemplo n.º 17
0
		public bool CreateOrActivate(String TaskName, String FullExecuteableFileName, TimeSpan RetryIntervall)
			{
			//if (!IsAdministrator())
			//	return false;
			using (TaskService taskService = new TaskService())
				{
				Task task = taskService.FindTask(TaskName);
				if (task == null)
					{
					TaskDefinition taskDefinition = CreateTask(taskService, TaskName, RetryIntervall);
					taskDefinition.Actions.Add(new ExecAction(FullExecuteableFileName));
					
					taskDefinition.RegistrationInfo.Description = $"WPMedia created Task for " +
									$"{Path.GetFileNameWithoutExtension(FullExecuteableFileName)}";
					taskDefinition.Settings.MultipleInstances = TaskInstancesPolicy.IgnoreNew;
					taskDefinition.Settings.AllowDemandStart = true;
					taskDefinition.Settings.AllowHardTerminate = false;
					taskDefinition.Settings.DisallowStartIfOnBatteries = false;
					taskDefinition.RegistrationInfo.Author = "WPMediaAutoRegistration";
					if (taskDefinition.Validate())
						task = taskService.RootFolder.RegisterTaskDefinition(TaskName, taskDefinition);
					else
						throw new Exception($"{TaskName} Scheduling for {FullExecuteableFileName} failed");
					}
				task.Enabled = true;
				}
			return true;
			}
Ejemplo n.º 18
0
 public static bool StartupTaskExists()
 {
     using (TaskService _taskService = new TaskService())
     {
         return _taskService.FindTask(_taskName) != null;
     }
 }
Ejemplo n.º 19
0
        public void SaveTask(string name, string time, string day, string route, int posicion, string accion)
        {
            using (TaskService ts = new TaskService())
            {
                TaskDefinition td = ts.NewTask();
                td.RegistrationInfo.Description = accion;

                WeeklyTrigger week = new WeeklyTrigger();

                week.StartBoundary = Convert.ToDateTime(DateTime.Today.ToShortDateString() + " " + time);
                week.WeeksInterval = 1;
                switch (day)
                {
                    case "Monday":
                        week.DaysOfWeek = Microsoft.Win32.TaskScheduler.DaysOfTheWeek.Monday;
                        break;
                    case "Tuesday":
                        week.DaysOfWeek = Microsoft.Win32.TaskScheduler.DaysOfTheWeek.Tuesday;
                        break;
                    case "Wednesday":
                        week.DaysOfWeek = Microsoft.Win32.TaskScheduler.DaysOfTheWeek.Wednesday;
                        break;
                    case "Thursday":
                        week.DaysOfWeek = Microsoft.Win32.TaskScheduler.DaysOfTheWeek.Thursday;
                        break;
                    case "Friday":
                        week.DaysOfWeek = Microsoft.Win32.TaskScheduler.DaysOfTheWeek.Friday;
                        break;
                    case "Saturday":
                        week.DaysOfWeek = Microsoft.Win32.TaskScheduler.DaysOfTheWeek.Saturday;
                        break;
                    case "Sunday":
                        week.DaysOfWeek = Microsoft.Win32.TaskScheduler.DaysOfTheWeek.Sunday;
                        break;
                    default:
                        break;

                }
                td.Triggers.Add(week);
                string turn_on;
                if (chkTurnOn.Checked)
                {
                    turn_on = " T";
                }
                else
                {
                    turn_on = " F";
                }

                if (posicion != -1)
                {
                    td.Actions.Add(new ExecAction(route, posicion.ToString() + turn_on, null));
                }
                else {
                    td.Actions.Add(new ExecAction(route, posicion.ToString() + turn_on, null));
                }
                ts.RootFolder.RegisterTaskDefinition(name, td);
            }
        }
Ejemplo n.º 20
0
 public List <ComputerProgram> GetScheduledTasks()
 {
     using (WinTaskScheduler.TaskService ts = new WinTaskScheduler.TaskService())
     {
         EnumFolderTasks(ts.RootFolder);
     }
     return(Tasks);
 }
Ejemplo n.º 21
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);
 }
Ejemplo n.º 22
0
 private void CheckTaskTimer()
 {
     using (var ts = new TaskService())
     {
             DateTime taskRuntime = ts.RootFolder.Tasks.Single(t => t.Name.Equals("GitUpdater")).NextRunTime;
             LoggingSection.Items.Add("Next scheduled update:  " + taskRuntime.ToString());
     }
 }
        public void Init()
        {
            _taskServiceConvertorFactory = new Mock<ITaskServiceConvertorFactory>();
            _nativeService = new TaskService();//localhost
            _nativeTask = _nativeService.NewTask();//actually a definition , not an actual task
            _nativeInstance = _nativeTask.Actions;

        }
Ejemplo n.º 24
0
        public static bool PersistTask(bool startAtLogon, bool startForAllUsers)
        {
            WinTasks.TaskService ts = new WinTasks.TaskService();
            try
            {
                WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent();
                bool isElevated = (new WindowsPrincipal(currentIdentity).IsInRole(WindowsBuiltInRole.Administrator));
                WinTasks.Task task = ts.FindTask(Application.ProductName, false);

                if (startAtLogon)
                {
                    if (startForAllUsers && !isElevated)
                    {
                        return PersistTaskElevated(startAtLogon, startForAllUsers);
                    }
                    else
                    {
                        WinTasks.LogonTrigger trigger = (WinTasks.LogonTrigger)WinTasks.LogonTrigger.CreateTrigger(WinTasks.TaskTriggerType.Logon);
                        trigger.Enabled = true;
                        trigger.StartBoundary = DateTime.Today;
                        if (startForAllUsers)
                            trigger.UserId = null;
                        else
                            trigger.UserId = currentIdentity.Name;

                        WinTasks.ExecAction action = (WinTasks.ExecAction)WinTasks.ExecAction.CreateAction(WinTasks.TaskActionType.Execute);
                        action.Path = Application.ExecutablePath;
                        action.WorkingDirectory = System.IO.Path.GetDirectoryName(Application.ExecutablePath);

                        if (task == null)
                        {
                            task = ts.AddTask(Application.ProductName, trigger, action, currentIdentity.Name);
                        }
                        else
                        {
                            task.Definition.Triggers.Clear();
                            task.Definition.Triggers.Add(trigger);
                            task.Definition.Actions.Clear();
                            task.Definition.Actions.Add(action);
                            task.RegisterChanges();
                        }
                    }
                }
                else if (task != null)
                {
                    ts.GetFolder("\\").DeleteTask(task.Name);
                }
            }
            catch
            {
                return false;
            }
            finally
            {
                ts.Dispose();
            }
            return true;
        }
Ejemplo n.º 25
0
        private void btnInput_Click(object sender, EventArgs e)
        {
            string strTaskID = "";
            string appPath = System.Configuration.ConfigurationManager.AppSettings["AutoGetOdds"];
            Application.DoEvents();
            Cursor.Current = Cursors.WaitCursor;

            try
            {
                // Get the service on the local machine
                TaskService ts = new TaskService();
                // Delete Schedules
                DataTable dt = oddBO.GetSchedules(1);
                foreach (DataRow dr in dt.Rows)
                {
                    strTaskID = dr["TaskID"].ToString();
                    if (ts.FindTask(strTaskID, true) != null)
                    {
                        // Remove the task we just created
                        ts.RootFolder.DeleteTask(strTaskID);
                    }
                    // Delete schedules follow taskid
                    oddBO.DeleleSchedules(strTaskID);
                }
                DateTime currDate = dtpDate.Value;
                // Create Schedules
                dt = oddBO.GetSchedules(0, currDate);
                foreach (DataRow dr in dt.Rows)
                {
                    strTaskID = dr["TaskID"].ToString();
                    // Create a new task definition and assign properties
                    TaskDefinition td = ts.NewTask();

                    Trigger t = new TimeTrigger();
                    t.StartBoundary = Convert.ToDateTime(dr["RunTime"].ToString());

                    td.RegistrationInfo.Description = "Get odd at " + dr["RunTime"].ToString();

                    // Create a trigger that will fire the task at this time every other day
                    td.Triggers.Add(t);

                    // Create an action that will launch Notepad whenever the trigger fires
                    td.Actions.Add(new ExecAction(appPath, "\"" + strTaskID + "\"", null));

                    // Register the task in the root folder
                    ts.RootFolder.RegisterTaskDefinition(strTaskID, td);
                }
                MessageBox.Show("Schedules have inputed successfully!", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                Cursor.Current = Cursors.WaitCursor;
            }
        }
Ejemplo n.º 26
0
 public static bool UnsetAutostart()
 {
     // Get the service on the local machine
     using (TaskService ts = new TaskService())
     {
         ts.RootFolder.DeleteTask("Touchmote");
         return true;
     }
 }
Ejemplo n.º 27
0
 public void TaskShedulerWrapper_TaskFolder_Construct()
 {
     var service = new TaskService();
     TaskFolder folder = service.RootFolder;
     var df = new Dev2TaskFolder(new TaskServiceConvertorFactory(),folder);
     Assert.AreEqual(df.Instance,folder);
     Assert.AreEqual(df.Name,folder.Name);
     Assert.AreEqual(df.Path,folder.Path);
     Assert.AreEqual(df.Tasks.Count(),folder.Tasks.Count);
 }
Ejemplo n.º 28
0
        public static void Uninstall(string name)
        {
            if (!IsTaskInstalled(name))
            {
                return;
            }

            using (var ts = new Scheduler.TaskService())
                ts.RootFolder.DeleteTask(name);
        }
Ejemplo n.º 29
0
        public static void DisableLaunchOnStartup()
        {
            using (var taskService = new TaskService())
            {
                var lastTaskName = ApplicationSettings.LaunchOnLoginTask;
                if (!string.IsNullOrWhiteSpace(lastTaskName))
                    taskService.RootFolder.DeleteTask(lastTaskName);

                ApplicationSettings.LaunchOnLoginTask = null;
            }
        }
Ejemplo n.º 30
0
        public void Init()
        {
            _taskService = new TaskService();

            var newTask = _taskService.NewTask();
            var action = new ExecAction("bob.exe");
            newTask.Actions.Add(action);
            newTask.Triggers.Add(new DailyTrigger());
            _taskService.RootFolder.RegisterTaskDefinition("UnitTestTask",newTask);
            _factory = new Mock<ITaskServiceConvertorFactory>();
        }
Ejemplo n.º 31
0
 private bool checkTaskIsScheduled()
 {
     TaskIsScheduled = false;
     using (Scheduler.TaskService tsrv = new Scheduler.TaskService()) {
         if (tsrv.AllTasks.Any(t => t.Name == _taskName))
         {
             TaskIsScheduled = true;
         }
     }
     return(TaskIsScheduled);
 }
Ejemplo n.º 32
0
 public ScheduledTask(string taskName, string taskDescription)
 {
     this.taskName = taskName;
     this.taskDescription = taskDescription;
     task = new TaskService();
     taskDef = task.NewTask();
     this.serialActions = new List<SerialAction>();
     this.serialTriggers = new List<SerialTrigger>();
     this.triggers = new List<Trigger>();
     this.actions = new List<ExecAction>();
 }
Ejemplo n.º 33
0
 private static TaskFolder loadTaskFolder() {
     TaskService ts = new TaskService();
     TaskFolder folder;
     try {
         folder = ts.GetFolder(@"\"+Constants.TASK_SCHEDULER_FOLDER);
     }
     catch (FileNotFoundException) {
         folder = ts.RootFolder.CreateFolder(@"\"+Constants.TASK_SCHEDULER_FOLDER);
     }
     return folder;
 }
Ejemplo n.º 34
0
 private void RemoveStartupTask()
 {
     try
     {
         using (Microsoft.Win32.TaskScheduler.TaskService tastService = new Microsoft.Win32.TaskScheduler.TaskService())
         {
             tastService.RootFolder.DeleteTask(BrandName, false);
             return;
         }
     }
     catch (Exception ex)
     {
         _logger.Debug(ex, "Unable to remove the startup task ");
     }
 }
Ejemplo n.º 35
0
 public bool IsExist(string name)
 {
     try
     {
         using (var ts = new Microsoft.Win32.TaskScheduler.TaskService())
         {
             return(EnumTasks(ts.RootFolder).
                    FirstOrDefault(task => task.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase)) != null);
         }
     }
     catch (Exception e)
     {
         this._LogService.Error(e.Message);
         throw;
     }
 }
Ejemplo n.º 36
0
        /// <summary>
        /// Runs the actual checks, sets the Problem count and string
        /// </summary>
        /// <returns></returns>
        public int Check()
        {
            // check for the correct setup, if one of the checks fails, exit right away.
            // with the new wrapper, it seems to work without being an admin
            //     if (!IsAdmin()) return SetProblem(AppName + " does not run as an administrator. This is required");
            if (Environment.OSVersion.Version.Major < 6)
            {
                return(SetProblem("Windows Vista or newer is required"));
            }
            if (!IsServiceRunning())
            {
                return(SetProblem("The Task Scheduler service is not running"));
            }
            if (RootFolderPattern == "")
            {
                return(SetProblem("No RootFolderPattern set, check your config file."));
            }

            try
            {
                using (wts.TaskService ts = new wts.TaskService())
                {
                    wts.TaskFolder root = ts.RootFolder;

                    if (CheckRootTasks)
                    {
                        CheckTasks(root);
                    }

                    ProcessFolder(root, RootFolderPattern);
                }
            }
            catch (Exception ex)
            {
                Exceptions.Log(ex);
                Failures.Add(new Failure
                {
                    Name    = "Application Exception",
                    Path    = ex.Message,
                    LastRun = DateTime.Now,
                    Result  = _appErrorId,
                });
            }

            // return the number of problems found
            return(Failures.Count);
        }
Ejemplo n.º 37
0
        public bool Delete(TaskSchedulerItem item)
        {
            try
            {
                using (var ts = new Microsoft.Win32.TaskScheduler.TaskService())
                {
                    ts.RootFolder.DeleteTask(item.Name, true);
                }

                return(true);
            }
            catch (Exception e)
            {
                this._LogService.Error(e.Message);
                return(false);
            }
        }
Ejemplo n.º 38
0
        public static void TrySetLaunchAtStartup(bool enabled, string username = null, string userpassword = null)
        {
            string name = Application.ProductName;

            using (MW32TS.TaskService service = new MW32TS.TaskService())
            {
                TryDeleteTasksByName(name);

                if (!enabled)
                {
                    return;
                }

                MW32TS.LogonTrigger trigger = new MW32TS.LogonTrigger();


                // MW32TS.BootTrigger trigger = new MW32TS.BootTrigger();
                // trigger.Delay = new TimeSpan(0, 0, 5);
                //trigger.Enabled = true;

                MW32TS.ExecAction action = new MW32TS.ExecAction(Application.ExecutablePath, null, null);
                action.WorkingDirectory = Application.StartupPath;

                MW32TS.TaskDefinition definition = service.NewTask();
                definition.RegistrationInfo.Description = "Launches App At Startup";
                definition.Triggers.Add(trigger);
                definition.Actions.Add(action);

                definition.Principal.RunLevel = MW32TS.TaskRunLevel.Highest;
                //definition.Principal.
                if (!username.IsNullOrEmpty())
                {
                    service.UserName = username;
                }

                if (!userpassword.IsNullOrEmpty())
                {
                    service.UserPassword = userpassword;
                }

                service.RootFolder.RegisterTaskDefinition(name, definition);
            }
        }
Ejemplo n.º 39
0
        private static bool CheckTaskName(string taskName)
        {
            bool result = false;

            using (Microsoft.Win32.TaskScheduler.TaskService ts = new Microsoft.Win32.TaskScheduler.TaskService())
            {
                using (Microsoft.Win32.TaskScheduler.TaskFolder taskFolder = ts.GetFolder(@"\"))
                {
                    foreach (Task t in taskFolder.Tasks)
                    {
                        if (t.Name.Contains(taskName))
                        {
                            result = true;
                        }
                    }
                }
            }

            return(result);
        }
Ejemplo n.º 40
0
 public static void DeleteScheduledTasks()
 {
     try
     {
         using (TS.TaskService ts = new TS.TaskService())
         {
             foreach (TS.Task t in ts.RootFolder.Tasks)
             {
                 if (t.Name.StartsWith("WinCertes"))
                 {
                     ts.RootFolder.DeleteTask(t.Name, false);
                 }
             }
         }
     }
     catch (Exception e)
     {
         logger.Error("Unable to read Scheduled Task status" + e.Message);
     }
 }
Ejemplo n.º 41
0
        /// <summary>
        /// Creates the windows scheduled task
        /// </summary>
        /// <param name="domains"></param>
        /// <param name="taskName"></param>
        public static void CreateScheduledTask(string taskName, List <string> domains, int extra)
        {
            if (taskName == null)
            {
                return;
            }
            try
            {
                using (TS.TaskService ts = new TS.TaskService())
                {
                    // Create a new task definition and assign properties
                    TS.TaskDefinition td = ts.NewTask();
                    td.RegistrationInfo.Description = "Manages certificate using ACME";

                    // We need to run as SYSTEM user
                    td.Principal.UserId = @"NT AUTHORITY\SYSTEM";

                    // Create a trigger that will fire the task at this time every other day
                    td.Triggers.Add(new TS.DailyTrigger {
                        DaysInterval = 2
                    });
                    String extraOpt = "";

                    if (extra > -1)
                    {
                        extraOpt = "--extra=" + extra.ToString() + " ";
                    }
                    // Create an action that will launch Notepad whenever the trigger fires
                    td.Actions.Add(new TS.ExecAction("WinCertes.exe", extraOpt + "-d " + String.Join(" -d ", domains), Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)));

                    // Register the task in the root folder
                    ts.RootFolder.RegisterTaskDefinition($"WinCertes - {taskName}", td);
                }
                logger.Info($"Scheduled Task \"WinCertes - {taskName}\" created successfully");
            }
            catch (Exception e)
            {
                logger.Error("Unable to create Scheduled Task" + e.Message);
            }
        }
Ejemplo n.º 42
0
        public bool ScheduleTask(string exeLocation)
        {
            try {
                using (Scheduler.TaskService tsrv = new Scheduler.TaskService()) {
                    //task for interval
                    tsrv.Execute(exeLocation)
                    .InWorkingDirectory(Path.GetDirectoryName(exeLocation))
                    .WithArguments(_taskArgs)
                    .Once()
                    .Starting(DateTime.Now)
                    .RepeatingEvery(TimeSpan.FromSeconds(_taskIntervalSeconds))
                    .AsTask(_taskName);

                    setupTask(_taskName);
                }
            } catch (Exception e) {
                MessageBox.Show($"Error scheduling task. Try changing <AdminsSytemUserGroup> or <TaskInterval> in Settings.xml.\nOriginal mesage: {e.Message}", "Task scheduling error", MessageBoxButton.OK,
                                MessageBoxImage.Error);
                UnScheduleTask();
            }
            return(checkTaskIsScheduled());
        }
Ejemplo n.º 43
0
 public static bool IsScheduledTaskCreated()
 {
     try
     {
         using (TS.TaskService ts = new TS.TaskService())
         {
             foreach (TS.Task t in ts.RootFolder.Tasks)
             {
                 if (t.Name.StartsWith("WinCertes"))
                 {
                     return(true);
                 }
             }
         }
         return(false);
     }
     catch (Exception e)
     {
         logger.Error("Unable to read Scheduled Task status" + e.Message);
         return(false);
     }
 }
Ejemplo n.º 44
0
        private void RefreshTasks()
        {
            DGV_taskBackumsoutlook.Rows.Clear();

            using (Microsoft.Win32.TaskScheduler.TaskService ts = new Microsoft.Win32.TaskScheduler.TaskService())
            {
                using (Microsoft.Win32.TaskScheduler.TaskFolder taskFolder = ts.GetFolder(@"\"))
                {
                    foreach (Task t in taskFolder.Tasks)
                    {
                        if (t.Name.Contains("backupmsoutlook_"))
                        {
                            TaskDefinition td      = t.Definition;
                            string         lastRun = t.LastRunTime.ToString();
                            if (lastRun.Contains("1899"))
                            {
                                lastRun = string.Empty;
                            }
                            string actions = td.Actions[0].ToString();
                            if (actions.Contains("\t"))
                            {
                                actions = actions.Replace("\t", " -> ");
                            }
                            string[] row = new string[] { t.Name, t.State.ToString(), actions, t.NextRunTime.ToString(), lastRun, "0x" + t.LastTaskResult, td.RegistrationInfo.Author, td.RegistrationInfo.Date.ToString() };
                            DGV_taskBackumsoutlook.Rows.Add(row);
                            DGV_taskBackumsoutlook.Rows[DGV_taskBackumsoutlook.Rows.Count - 1].Selected = true;
                        }
                    }
                }
            }

            if (DGV_taskBackumsoutlook.Rows.Count > 0)
            {
                DGV_taskBackumsoutlook.Rows[0].Cells[0].Selected = false;
                DGV_taskBackumsoutlook.Rows[DGV_taskBackumsoutlook.Rows.Count - 1].Selected = true;
            }
        }
Ejemplo n.º 45
0
 internal TaskEventArgs([NotNull] TaskEvent evt, TaskService ts = null)
 {
     TaskEvent   = evt;
     TaskPath    = evt.TaskPath;
     taskService = ts;
 }
 internal RunningTaskEnumerator(TaskService svc, V2Interop.IRunningTaskCollection iTaskColl)
 {
     this.svc = svc;
     v2Svc    = svc.v2TaskService;
     iEnum    = iTaskColl.GetEnumerator();
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="TaskOptionsEditor"/> class.
 /// </summary>
 /// <param name="service">A <see cref="TaskService"/> instance.</param>
 /// <param name="td">An optional <see cref="TaskDefinition"/>. Leaving null creates a new task.</param>
 /// <param name="editable">If set to <c>true</c> the task will be editable in the dialog.</param>
 /// <param name="registerOnAccept">If set to <c>true</c> the task will be registered when Ok is pressed.</param>
 public TaskOptionsEditor(TaskService service, TaskDefinition td = null, bool editable = true, bool registerOnAccept = true) : this()
 {
     this.Editable = editable;
     this.Initialize(service, td);
     this.RegisterTaskOnAccept = registerOnAccept;
 }
 internal V1RunningTaskEnumerator(TaskService svc)
 {
     this.svc = svc;
     tEnum    = new TaskCollection.V1TaskEnumerator(svc);
 }
 internal RunningTaskCollection(TaskService svc, V2Interop.IRunningTaskCollection iTaskColl)
 {
     this.svc = svc;
     v2Svc    = svc.v2TaskService;
     v2Coll   = iTaskColl;
 }
 internal RunningTaskCollection(TaskService svc)
 {
     this.svc = svc;
     v1TS     = svc.v1TaskScheduler;
 }
Ejemplo n.º 51
0
 internal TaskFolder(TaskService svc)
 {
     this.TaskService = svc;
     v1List           = svc.v1TaskScheduler;
 }
Ejemplo n.º 52
0
 internal RunningTaskCollection([NotNull] TaskService svc) => this.svc = svc;
Ejemplo n.º 53
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TaskEventWatcher" /> class watching only
 /// those events for the task with the provided path on the local machine.
 /// </summary>
 /// <param name="taskPath">The full path (folders and name) of the task to watch.</param>
 /// <param name="taskService">The task service.</param>
 /// <exception cref="System.ArgumentException">$Invalid task name: {taskPath}</exception>
 public TaskEventWatcher(string taskPath, TaskService taskService = null) : this(taskService ?? TaskService.Instance)
 {
     InitTask(taskPath);
 }
 internal TaskCollection(TaskService svc, Regex filter = null)
 {
     this.svc    = svc;
     this.Filter = filter;
     v1TS        = svc.v1TaskScheduler;
 }
 private void ResetTaskService()
 {
     ts = TaskService.Instance;
 }
Ejemplo n.º 56
0
 internal TaskFolder(TaskService svc, V2Interop.ITaskFolder iFldr)
 {
     this.TaskService = svc;
     v2Folder         = iFldr;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="TaskEventWatcher" /> class.
 /// </summary>
 /// <param name="folder">The task folder to watch.</param>
 /// <param name="taskFilter">The filter for task names using standard file system wildcards. Use "*" to include all tasks.</param>
 /// <param name="includeSubfolders">if set to <c>true</c> include events from tasks subfolders.</param>
 /// <param name="taskService">The task service.</param>
 public TaskEventWatcher(string folder, string taskFilter, bool includeSubfolders, TaskService taskService = null) : this(taskService ?? TaskService.Instance)
 {
     InitTask(folder, taskFilter, includeSubfolders);
 }
Ejemplo n.º 58
0
 public static bool IsTaskInstalled(string name)
 {
     using (var ts = new Scheduler.TaskService())
         return(ts.FindTask(name) != null);
 }
Ejemplo n.º 59
0
 private TaskEventWatcher(TaskService ts)
 {
     TaskService = ts;
     Filter      = new EventFilter(this);
 }