Example #1
0
        public bool PushAlarmToWinScheduler(Alarm _alarm)
        {
            /*            try
             *          {
             *              Environment.SetEnvironmentVariable("ALARMCLOCKPATH", Process.GetCurrentProcess().MainModule.FileName, EnvironmentVariableTarget.Machine);
             *          }
             *          catch (Exception ex)
             *          {
             *              new ToastViewModel().ShowError(string.Format("Failed to set Environment Variable ({0})", ex.Message));
             *          }*/

            try
            {
                TaskDefinition td = AlarmScheduler(_alarm);
                if (!td.Validate())
                {
                    throw new Exception("Alarm validation failed");
                }
                // Register the task in the root folder of the local machine
                string _alarmName = "ALARM_" + new Random().Next();
                TaskService.Instance.RootFolder.RegisterTaskDefinition(_alarmName, td);
            }
            catch (Exception ex)
            {
                new ToastViewModel().ShowError(ex.Message);
                System.Media.SystemSounds.Beep.Play();
                return(false);
            }

            new ToastViewModel().ShowSuccess("Alarm set successfully");
            System.Media.SystemSounds.Asterisk.Play();
            return(true);
        }
        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");
        }