Ejemplo n.º 1
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
             {
             }
         }
     }
 }
Ejemplo n.º 2
0
        /// <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"));
            }
        }
Ejemplo n.º 3
0
        private static Task loadTask(string name, TaskFolder folder = null)
        {
            if (folder == null)
            {
                folder = loadTaskFolder();
            }
            TaskCollection tasks = folder.GetTasks();

            return(tasks.FirstOrDefault(x => x.Name == name));
        }
Ejemplo n.º 4
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);
                    }
                }
            }
        }
Ejemplo n.º 5
0
        public static Task getTask(string taskName, TaskService ts)
        {
            TaskFolder tf = getTaskFolder(ts);

            if (tf == null)
            {
                return(null);
            }

            Regex          filter     = new Regex(taskName);
            TaskCollection collection = tf.GetTasks(filter);

            if (collection == null || collection.Count == 0)
            {
                return(null);
            }

            return(collection[0]);
        }
Ejemplo n.º 6
0
        public void SynchronizeSchedules(ExecutionLogInterface log, bool useCurrentUser)
        {
            int           count = 0, errorCount = 0, taskDeleted = 0;
            StringBuilder errorSummary = new StringBuilder("");

            Repository repository = Repository.Instance.CreateFast();

            try
            {
                log.Log("Starting Report Schedules Synchronization\r\n");

                if (!Helper.IsMachineAdministrator() && !useCurrentUser)
                {
                    log.Log("WARNING: For this tool, we recommend to execute the 'Server Manager' application with the option 'Run as administrator'\r\n");
                }

                SynchronizeSchedules(log, repository.ReportsFolder, repository, ref count, ref errorCount, errorSummary, useCurrentUser);
                log.Log("Checking personal folders\r\n");
                SynchronizeSchedules(log, repository.PersonalFolder, repository, ref count, ref errorCount, errorSummary, useCurrentUser);

                log.Log("Checking for Orphan schedules\r\n");

                if (repository.UseWebScheduler)
                {
                    SealReportScheduler.Instance.GetSchedules();
                }
                else
                {
                    TaskService taskService = new TaskService();
                    TaskFolder  taskFolder  = taskService.RootFolder.SubFolders.FirstOrDefault(i => i.Name == repository.Configuration.TaskFolderName);
                    if (taskFolder != null)
                    {
                        foreach (Task task in taskFolder.GetTasks())
                        {
                            log.Log("Checking task '{0}'", task.Name);
                            try
                            {
                                string reportPath   = ReportSchedule.GetTaskSourceDetail(task.Definition.RegistrationInfo.Source, 0);
                                string reportGUID   = ReportSchedule.GetTaskSourceDetail(task.Definition.RegistrationInfo.Source, 1);
                                string scheduleGUID = ReportSchedule.GetTaskSourceDetail(task.Definition.RegistrationInfo.Source, 3);
                                Report report       = ReportExecution.GetScheduledReport(taskFolder, reportPath, reportGUID, scheduleGUID, repository);
                                if (report != null)
                                {
                                    ReportSchedule schedule = ReportExecution.GetReportSchedule(taskFolder, report, scheduleGUID);
                                    if (schedule == null)
                                    {
                                        taskDeleted++;
                                        log.Log("WARNING: Unable to find schedule '{0}' in report '{1}'. Task has been deleted.", scheduleGUID, report.FilePath);
                                    }
                                }
                                else
                                {
                                    taskDeleted++;
                                    log.Log("WARNING: Unable to find report '{0}' for schedule '{1}'. Report tasks have been deleted.", reportGUID, scheduleGUID);
                                }
                            }
                            catch (Exception ex)
                            {
                                errorCount++;
                                log.LogRaw("ERROR\r\n");
                                log.Log(ex.Message);
                                errorSummary.AppendFormat("\r\nTask '{0}': {1}\r\n", task.Name, ex.Message);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                log.Log("\r\n[UNEXPECTED ERROR RECEIVED]\r\n{0}\r\n", ex.Message);
            }
            log.Log("Report Schedules Synchronization terminated\r\n");

            log.Log("SUMMARY: {0} Report(s) checked, {1} Task(s) deleted, {2} Error(s) detected.\r\n{3}", count, taskDeleted, errorCount, errorSummary);
            if (errorCount == 0)
            {
                log.Log("Youpi, pas d'erreur !");
            }
        }
Ejemplo n.º 7
0
        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");
        }
Ejemplo n.º 8
0
 private bool FindTaskInFolder(TaskFolder fld, Regex taskName, ref List<Task> results, bool recurse = true)
 {
     results.AddRange(fld.GetTasks(taskName));
     if (recurse)
         foreach (TaskFolder folder in fld.SubFolders)
             if (FindTaskInFolder(folder, taskName, ref results, recurse))
                 return true;
     return false;
 }