public void RemoveTask()
 {
     using (TaskService taskService = new TaskService())
     {
         TaskFolder taskFolder = taskService.GetFolder(folder);
         try
         {
             taskFolder.DeleteTask(light);
         }
         catch
         {
         }
         try
         {
             taskFolder.DeleteTask(dark);
         }
         catch
         {
         }
         try
         {
             taskFolder.DeleteTask(updater);
         }
         catch
         {
         }
         try
         {
             taskService.RootFolder.DeleteFolder(folder);
         }
         catch
         {
         }
     }
 }
示例#2
0
 public void RemoveTask()
 {
     using (TaskService taskService = new TaskService())
     {
         TaskFolder taskFolder = taskService.GetFolder(folder);
         try
         {
             taskFolder.DeleteTask(light, false);
         }
         catch
         {
         }
         try
         {
             taskFolder.DeleteTask(dark, false);
         }
         catch
         {
         }
         try
         {
             taskFolder.DeleteTask(hibernation, false);
         }
         catch
         {
         }
         try
         {
             taskFolder.DeleteTask(updater, false);
         }
         catch
         {
         }
         try
         {
             taskFolder.DeleteTask(appupdater, false);
         }
         catch
         {
         }
         try
         {
             taskService.RootFolder.DeleteFolder(folder, false);
         }
         catch
         {
         }
     }
 }
 public void RemoveTask()
 {
     using (TaskService taskService = new TaskService())
     {
         try
         {
             TaskFolder taskFolder = taskService.RootFolder;
             taskFolder.DeleteTask("Auto-Night Mode Light");
             taskFolder.DeleteTask("Auto-Night Mode Dark");
         }
         catch (Exception)
         {
         }
     }
 }
示例#4
0
        private static void OnRemove(Task task, ref bool returnValue)
        {
            TaskService Scheduler  = task.TaskService;
            TaskFolder  RootFolder = Scheduler.RootFolder;

            RootFolder.DeleteTask(task.Name, false);
        }
示例#5
0
 public void RemoveAllTasks()
 {
     using (TaskService taskService = new TaskService())
     {
         TaskFolder taskFolder = taskService.GetFolder(folder);
         if (taskFolder != null)
         {
             foreach (var v in taskFolder.GetTasks())
             {
                 try
                 {
                     taskFolder.DeleteTask(v.ToString(), false);
                     Console.WriteLine("Deleted Task: " + v.ToString());
                 }
                 catch
                 {
                 }
             }
             try
             {
                 taskService.RootFolder.DeleteFolder(folder, false);
             }
             catch
             {
             }
         }
     }
 }
        /// <summary>
        /// Deletes all schedulers.
        /// </summary>
        public void DeleteAllSchedulers()
        {
            try
            {
                var        taskScheduler             = new TaskService();
                TaskFolder taskFolder                = taskScheduler.GetFolder("\\" + PullDataScheduler.SchedulerGroupName);
                IEnumerable <TaskFolder> taskFolders = GetTaskFolder(taskScheduler, PullDataScheduler.SchedulerGroupName);

                if (taskFolders.Any())
                {
                    TaskCollection tasks = taskFolder.GetTasks();
                    if (tasks != null)
                    {
                        foreach (Task task in tasks)
                        {
                            if (task.State == TaskState.Running)
                            {
                                task.Stop();
                            }
                            taskFolder.DeleteTask(task.Name, false);
                        }
                    }
                }
                taskFolder = taskScheduler.GetFolder("\\");
                taskFolder.DeleteFolder(PullDataScheduler.SchedulerGroupName, false);
            }
            catch (Exception exception)
            {
                Logger.LogMessage(exception.Message, "DeleteSchedulers", LogType.Error, exception);
                //NotificationHelper.ShowMessage(exception.Message, ResourceHelper.GetResourceValue("CaptionError"));
            }
        }
示例#7
0
        /// <summary>
        /// Deletes the scheduled task associated with the specified mirror task
        /// if it exists.
        /// </summary>
        public void Delete(MirrorTask mirrorTask)
        {
            if (mirrorTask == null)
            {
                throw new ArgumentNullException("mirrorTask");
            }

            _folder.DeleteTask(GetName(mirrorTask), exceptionOnNotExists: false);
        }
示例#8
0
        public static void Delete(string name)
        {
            TaskFolder folder = loadTaskFolder();

            try {
                folder.DeleteTask(name);
            }
            catch (FileNotFoundException) { }
        }
示例#9
0
        private void B_removeSchedule_Click(object sender, EventArgs e)
        {
            Int32 selectedCellCount = DGV_taskBackumsoutlook.GetCellCount(DataGridViewElementStates.Selected);

            if (selectedCellCount > 0)
            {
                foreach (DataGridViewRow row in DGV_taskBackumsoutlook.Rows)
                {
                    if (row.Selected)
                    {
                        string       taskName = row.Cells[0].Value.ToString();
                        DialogResult dr       = MessageBox.Show("Are you sure, delete task name = " + taskName,
                                                                "Remove task",
                                                                MessageBoxButtons.YesNo,
                                                                MessageBoxIcon.Question);

                        if (dr == System.Windows.Forms.DialogResult.Yes)
                        {
                            Microsoft.Win32.TaskScheduler.TaskService ts = new TaskService();
                            try
                            {
                                using (TaskFolder taskFolder = ts.GetFolder(@"\"))
                                {
                                    try
                                    {
                                        taskFolder.DeleteTask(taskName);
                                        RefreshTasks();
                                        //MessageBox.Show(String.Format("Successfull delete task -> {0}", taskName), "Delete task", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                    }
                                    catch (Exception ex)
                                    {
                                        MessageBox.Show(String.Format("Failure delete task -> {0}\nError -> {1}", taskName, ex.Message), "Delete task", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                    }
                                }
                            }
                            finally
                            {
                                if (ts != null)
                                {
                                    ts.Dispose();
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                MessageBox.Show("Not selected task to delete",
                                "Delete task",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Information);
            }
        }
示例#10
0
 public static void deleteTask(string machineName, string taskName, SecurityOptions securityOptions)
 {
     using (TaskService ts = new TaskService(machineName, securityOptions.RunAsUser, Environment.UserDomainName, securityOptions.Password))
     {
         Task task = getTask(taskName, ts);
         if (task != null)
         {
             TaskFolder tf = getTaskFolder(ts);
             tf.DeleteTask(taskName);
         }
     }
 }
示例#11
0
        public void Cleanup()
        {
            _folder = _service.GetFolder("WarewolfTestFolder");
            foreach (var task in _folder.Tasks)
            {
                _folder.DeleteTask(task.Name, false);
            }

            _service.RootFolder.DeleteFolder("WarewolfTestFolder");
            _service.Dispose();
            _folder.Dispose();
        }
示例#12
0
 public void removeSchedule(Guid queueId)
 {
     try
     {
         using (TaskService ts = new TaskService())
         {
             TaskFolder tf = ts.GetFolder("SMSPortal");
             tf.DeleteTask("Queue_" + queueId.ToString());
         }
     }
     catch { }
 }
示例#13
0
        private void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor.Current = Cursors.WaitCursor;

                if (taskListView.SelectedIndex < 0)
                {
                    return;
                }

                if (string.IsNullOrEmpty(TaskNameSelected))
                {
                    return;
                }

                using (TaskService ts = new TaskService())
                {
                    if (!ts.RootFolder.SubFolders.Exists(TASK_FOLDER))
                    {
                        return;
                    }

                    TaskFolder tf = ts.GetFolder(TASK_FOLDER);

                    foreach (Task task in tf.Tasks)
                    {
                        if (task.Name != TaskNameSelected)
                        {
                            continue;
                        }

                        if (DialogResult.Yes == KryptonMessageBox.Show(this,
                                                                       @"Do you want to delete the selected task?",
                                                                       @"Delete Scheduled Task", MessageBoxButtons.YesNoCancel))
                        {
                            tf.DeleteTask(TaskNameSelected);
                            DisplayTaskScheduleItems();
                        }
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Fatal(ex);
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }
示例#14
0
        public static void RemoveAppUpdaterTask()
        {
            using TaskService taskService = new TaskService();
            TaskFolder taskFolder = taskService.GetFolder(folder);

            try
            {
                taskFolder.DeleteTask(appupdater, false);
            }
            catch
            {
            }
        }
示例#15
0
        public static void RemoveConnectedStandbyTask()
        {
            using TaskService taskService = new TaskService();
            TaskFolder taskFolder = taskService.GetFolder(folder);

            try
            {
                taskFolder.DeleteTask(connected, false);
            }
            catch
            {
            }
        }
 public void RemoveLocationTask()
 {
     using (TaskService taskService = new TaskService())
     {
         TaskFolder taskFolder = taskService.GetFolder(folder);
         try
         {
             taskFolder.DeleteTask(updater, false);
         }
         catch
         {
         }
     }
 }
 public void DeleteTask(string taskName)
 {
     try
     {
         using (TaskService ts = new TaskService())
         {
             TaskFolder folder = ts.FindTask(taskName).Folder;
             folder.DeleteTask(taskName);
         }
     } catch (Exception ex)
     {
         throw new Exception("Failed to remove task" + taskName + " On Local Server. " + ex.Message);
     }
 }
示例#18
0
        public static void RemoveTasks()
        {
            using TaskService taskService = new TaskService();
            TaskFolder taskFolder = taskService.GetFolder(folder);

            //fixme: properly do error handling in here
            try
            {
                taskFolder.DeleteTask(light, false);
            }
            catch
            {
            }
            try
            {
                taskFolder.DeleteTask(dark, false);
            }
            catch
            {
            }
            try
            {
                taskFolder.DeleteTask(hibernation, false);
            }
            catch
            {
            }
            try
            {
                taskFolder.DeleteTask(updater, false);
            }
            catch
            {
            }
            try
            {
                taskFolder.DeleteTask(appupdater, false);
            }
            catch
            {
            }
            try
            {
                taskFolder.DeleteTask(connected, false);
            }
            catch
            {
            }
            try
            {
                taskService.RootFolder.DeleteFolder(folder, false);
            }
            catch
            {
            }
        }
 public void DeleteTask(string taskName, string server, string username, string domain, string password)
 {
     try
     {
         using (TaskService ts = new TaskService(server, username, domain, password))
         {
             TaskFolder folder = ts.FindTask(taskName).Folder;
             folder.DeleteTask(taskName);
         }
     }
     catch (Exception ex)
     {
         throw new Exception("Failed to remove task: " + taskName + " on Server: " + server + " - " + ex.Message);
     }
 }
示例#20
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);
                    }
                }
            }
        }
示例#21
0
        public static void DeleteAllTasks()
        {
            try
            {
                TaskFolder folder = CreateRootFolder();

                foreach (Task task in folder.Tasks)
                {
                    folder.DeleteTask(task.Name);
                }

                Service.RootFolder.DeleteFolder(folder.Name, false);
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message);

                throw ex;
            }
        }
示例#22
0
        public static bool RemoveLogonTask()
        {
            using TaskService taskService = new TaskService();
            TaskFolder taskFolder = taskService.GetFolder(folder);

            if (taskFolder == null)
            {
                Logger.Debug("logon task does not exist (no taskFolder)");
                return(true);
            }
            try
            {
                taskFolder.DeleteTask(logon, false);
                return(true);
            }
            catch (Exception ex)
            {
                Logger.Error(ex, "failed removing logon task, ");
            }
            return(false);
        }
示例#23
0
        public bool ClearScheduledTask()
        {
            bool result = false;

            try
            {
                using (TaskService ts = new TaskService())
                {
                    TaskFolder tf = ts.GetFolder("BatchUpgrader");
                    foreach (Task task in tf.Tasks)
                    {
                        tf.DeleteTask(task.Name);
                    }
                    result = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Failed to clear all scheduled tasks.\n" + ex.Message, "Clear Task Scheduled Task", MessageBoxButton.OK);
            }
            return(result);
        }
示例#24
0
        public bool DeleteExistingTask(string taskName)
        {
            bool result = false;

            try
            {
                if (!string.IsNullOrEmpty(taskName))
                {
                    using (TaskService ts = new TaskService())
                    {
                        TaskFolder tf = ts.GetFolder("BatchUpgrader");
                        tf.DeleteTask(taskName);
                    }
                }
            }
            catch (Exception ex)
            {
                string message = ex.Message;
                //MessageBox.Show("Cannot delete the task named "+taskName+"\n"+ex.Message, "DeleteExisitngTask", MessageBoxButton.OK);
            }
            return(result);
        }
示例#25
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);
                                            }
        }
示例#26
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));
        }
示例#27
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));
        }
        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");
        }
        /// <summary>
        /// Method to rollback installation process.
        /// </summary>
        public static bool RollBack()
        {
            try
            {
                string shortcutFile = string.Concat(Environment.GetFolderPath(Environment.SpecialFolder.Startup), "\\CyberoamAuthManager.lnk");

                if (File.Exists(shortcutFile))
                {
                    File.Delete(shortcutFile);
                }

                if (Directory.Exists(TargetAppFolder))
                {
                    Directory.Delete(TargetAppFolder, true);
                }

                if (Directory.Exists(DataTargetAppFolder))
                {
                    Directory.Delete(DataTargetAppFolder, true);
                }

                using (TaskService ts = new TaskService())
                {
                    if (ts.RootFolder.Tasks.Exists(LoginTaskName))
                    {
                        try
                        {
                            ts.RootFolder.DeleteTask(LoginTaskName);
                        }
                        catch (Exception)
                        {
                        }
                    }

                    if (ts.RootFolder.Tasks.Exists(LogoutTaskName))
                    {
                        try
                        {
                            ts.RootFolder.DeleteTask(LogoutTaskName);
                        }
                        catch (Exception)
                        {
                        }
                    }

                    if (ts.RootFolder.SubFolders.Exists(TaskFolderName))
                    {
                        TaskFolder taskFolder = ts.GetFolder(TaskFolderName);
                        if (taskFolder.Tasks.Exists(LoginTaskName))
                        {
                            try
                            {
                                taskFolder.DeleteTask(LoginTaskName);
                            }
                            catch (Exception)
                            {
                            }
                        }

                        if (taskFolder.Tasks.Exists(LogoutTaskName))
                        {
                            try
                            {
                                taskFolder.DeleteTask(LogoutTaskName);
                            }
                            catch (Exception)
                            {
                            }
                        }

                        try
                        {
                            ts.RootFolder.SubFolders.Remove(taskFolder);
                        }
                        catch (Exception)
                        {
                        }
                    }
                }

                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
示例#30
0
 public static void Delete(string name)
 {
     folder.DeleteTask(name);
 }