Quantcast
Channel: Task Scheduler Managed Wrapper
Viewing all 2206 articles
Browse latest View live

New Post: trying to simply change tasks to disabled.

$
0
0
no, the task is still enabled via the UI and Code. but the register is successful in the history of the task. This is what is most strange.
I do have administrative rights to this test environment. AD domain admin.
the task is updated according to the history, but does not register the change.
I have tried connecting to remote server new TaskService(servername, adminuserid,, PW) with and without the id and PW to no avail.
the task shows a status of Ready,
and the trigger is also still at Enabled.
No errors.
  • <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
  • <System>
    <Provider Name="Microsoft-Windows-TaskScheduler" Guid="{DE7B24EA-73C8-4A09-985D-5BDADCFA9017}" />
    <EventID>140</EventID>
    <Version>0</Version>
    <Level>4</Level>
    <Task>140</Task>
    <Opcode>0</Opcode>
    <Keywords>0x8000000000000000</Keywords>
    <TimeCreated SystemTime="2015-03-11T17:16:50.183039000Z" />
    <EventRecordID>323807</EventRecordID>
    <Correlation />
    <Execution ProcessID="1484" ThreadID="10676" />
    <Channel>Microsoft-Windows-TaskScheduler/Operational</Channel>
    <Computer>aserver.ms.ds.uhc.com</Computer>
    <Security UserID="S-1-5-18" />
    </System>
  • <EventData Name="TaskUpdated">
    <Data Name="TaskName">\Testtask1</Data>
    <Data Name="UserName">ms\id</Data>
    </EventData>
    </Event>
  • <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
  • <System>
    <Provider Name="Microsoft-Windows-TaskScheduler" Guid="{DE7B24EA-73C8-4A09-985D-5BDADCFA9017}" />
    <EventID>142</EventID>
    <Version>0</Version>
    <Level>4</Level>
    <Task>142</Task>
    <Opcode>0</Opcode>
    <Keywords>0x8000000000000000</Keywords>
    <TimeCreated SystemTime="2015-03-11T17:16:49.902235400Z" />
    <EventRecordID>323806</EventRecordID>
    <Correlation />
    <Execution ProcessID="1484" ThreadID="12808" />
    <Channel>Microsoft-Windows-TaskScheduler/Operational</Channel>
    <Computer>servername.ms.ds.uhc.com</Computer>
    <Security UserID="S-1-5-18" />
    </System>
  • <EventData Name="TaskDisabled">
    <Data Name="TaskName">\Testtask1</Data>
    <Data Name="UserName">ms\id</Data>
    </EventData>
    </Event>

Commented Unassigned: Need to Set "RunOnlyIfLoggedOn" in Ver 2.0 [12031]

$
0
0
I've created a task with a trigger that starts a custom Windows Form application "At log on" of a specific user. In order for the task to succeed in running the application upon log on of the specific user, I must specify the specific user and their password when registering the task definition (ie: ts.RootFolder.RegisterTaskDefinition(taskName, td, TaskCreation.CreateOrUpdate...). I'm able to save/register the task, but the "Run whether user is logged on or not" option gets enabled under the "General > Security options" tab in the Task Manager. Thus, my application cannot start. When I manually change the Security option to "Run only when user is logged on" my application starts fine upon login. The problem is that I cannot set this option programmatically in ver 2.0 of the library.

In addition, I should not have to specify a password in the definition of the task if the "Run only when user is logged on" option is enabled because the user enters a password upon log on. When creating the task in the Task Scheduler manually, it does not prompt for a password.

How can I get this working so my application will start.
Comments: ** Comment from web user: jeffl012 **

Thank you. Here it is...

<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.3" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
<RegistrationInfo>
<Author></Author>
<Description>Launches Newtwork Connection Manager upon login.</Description>
</RegistrationInfo>
<Triggers>
<LogonTrigger>
<StartBoundary>1900-01-01T00:00:00</StartBoundary>
<Enabled>true</Enabled>
<UserId>JEFFL-PC\GUEST</UserId>
</LogonTrigger>
</Triggers>
<Principals>
<Principal id="Inteset_Launch_Network_Connection_Manager">
<UserId>JEFFL-PC\GUEST</UserId>
<LogonType>InteractiveToken</LogonType>
<RunLevel>HighestAvailable</RunLevel>
</Principal>
</Principals>
<Settings>
<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
<AllowHardTerminate>false</AllowHardTerminate>
<StartWhenAvailable>false</StartWhenAvailable>
<RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
<IdleSettings>
<Duration>PT10M</Duration>
<WaitTimeout>PT1H</WaitTimeout>
<StopOnIdleEnd>false</StopOnIdleEnd>
<RestartOnIdle>false</RestartOnIdle>
</IdleSettings>
<AllowStartOnDemand>true</AllowStartOnDemand>
<Enabled>true</Enabled>
<Hidden>true</Hidden>
<RunOnlyIfIdle>false</RunOnlyIfIdle>
<DisallowStartOnRemoteAppSession>false</DisallowStartOnRemoteAppSession>
<UseUnifiedSchedulingEngine>true</UseUnifiedSchedulingEngine>
<WakeToRun>false</WakeToRun>
<ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
<Priority>5</Priority>
</Settings>
<Actions Context="Network_Connection_Manager">
<Exec>
<Command>"M:\NetworkConnectionManager\NetworkConnectionManager.EXE"</Command>
<WorkingDirectory>M:\NetworkConnectionManager\</WorkingDirectory>
</Exec>
</Actions>
</Task>

New Post: How to Repetition.Duration indefinitely

$
0
0
I did try to use that but my task needs to be repeated hourly. So i have to set the trigger.Repetition.Interval to 1 hr timespan value and then while creating the task it complains that trigger.Repetition.Interval needs to be lower than trigger.repetition.duration

New Post: Converting TaskDefinition to work with Server 2003 R2

$
0
0
How to dynamically decide what to use for a remote computer ? forceV1=true or false?

New Post: Converting TaskDefinition to work with Server 2003 R2

$
0
0
If a server's version is Windows Server 2003 R2 or earlier or XP or earlier (major version <= 5) then you should force V1 (= true).

New Post: Windows 10 Support

$
0
0
I have just run the full bank of tests on Win10 Build 9926 w/o error, including the UI components. Please note the build and the errors in your response.

Commented Unassigned: Need to Set "RunOnlyIfLoggedOn" in Ver 2.0 [12031]

$
0
0
I've created a task with a trigger that starts a custom Windows Form application "At log on" of a specific user. In order for the task to succeed in running the application upon log on of the specific user, I must specify the specific user and their password when registering the task definition (ie: ts.RootFolder.RegisterTaskDefinition(taskName, td, TaskCreation.CreateOrUpdate...). I'm able to save/register the task, but the "Run whether user is logged on or not" option gets enabled under the "General > Security options" tab in the Task Manager. Thus, my application cannot start. When I manually change the Security option to "Run only when user is logged on" my application starts fine upon login. The problem is that I cannot set this option programmatically in ver 2.0 of the library.

In addition, I should not have to specify a password in the definition of the task if the "Run only when user is logged on" option is enabled because the user enters a password upon log on. When creating the task in the Task Scheduler manually, it does not prompt for a password.

How can I get this working so my application will start.
Comments: ** Comment from web user: dahall **

You cannot use UseUnifiedSchedulingEngine = true and interactive account. Set that value to false and all should work.

Commented Unassigned: Need to Set "RunOnlyIfLoggedOn" in Ver 2.0 [12031]

$
0
0
I've created a task with a trigger that starts a custom Windows Form application "At log on" of a specific user. In order for the task to succeed in running the application upon log on of the specific user, I must specify the specific user and their password when registering the task definition (ie: ts.RootFolder.RegisterTaskDefinition(taskName, td, TaskCreation.CreateOrUpdate...). I'm able to save/register the task, but the "Run whether user is logged on or not" option gets enabled under the "General > Security options" tab in the Task Manager. Thus, my application cannot start. When I manually change the Security option to "Run only when user is logged on" my application starts fine upon login. The problem is that I cannot set this option programmatically in ver 2.0 of the library.

In addition, I should not have to specify a password in the definition of the task if the "Run only when user is logged on" option is enabled because the user enters a password upon log on. When creating the task in the Task Scheduler manually, it does not prompt for a password.

How can I get this working so my application will start.
Comments: ** Comment from web user: jeffl012 **

The exported xml is from the task that works. I'm confused.


New Post: trying to simply change tasks to disabled.

$
0
0
Is this the correct process, seems to me that it should work?

New Post: Allows remote task creation when forcev1 = true ONLY

$
0
0
I have seen that if forceV1 is true, then the Server service in the client needs to be running, else it gives a "network path not found..." error.

But if forceV1 is false, Server service dependency is not there?

Can you pls confirm this and why is so?

Also, how to dynamically determine what value to use in forcev1?

Commented Unassigned: Need to Set "RunOnlyIfLoggedOn" in Ver 2.0 [12031]

$
0
0
I've created a task with a trigger that starts a custom Windows Form application "At log on" of a specific user. In order for the task to succeed in running the application upon log on of the specific user, I must specify the specific user and their password when registering the task definition (ie: ts.RootFolder.RegisterTaskDefinition(taskName, td, TaskCreation.CreateOrUpdate...). I'm able to save/register the task, but the "Run whether user is logged on or not" option gets enabled under the "General > Security options" tab in the Task Manager. Thus, my application cannot start. When I manually change the Security option to "Run only when user is logged on" my application starts fine upon login. The problem is that I cannot set this option programmatically in ver 2.0 of the library.

In addition, I should not have to specify a password in the definition of the task if the "Run only when user is logged on" option is enabled because the user enters a password upon log on. When creating the task in the Task Scheduler manually, it does not prompt for a password.

How can I get this working so my application will start.
Comments: ** Comment from web user: dahall **

The code below should generate the exact format of the XML file you provided:
```
using (var ts = new TaskService())
{
var td = ts.NewTask();
td.RegistrationInfo.Description = "Launches Network Connection Manager upon login.";
td.Principal.RunLevel = TaskRunLevel.Highest;
td.Settings.DisallowStartIfOnBatteries = false;
td.Settings.StopIfGoingOnBatteries = false;
td.Settings.AllowHardTerminate = false;
td.Settings.IdleSettings.StopOnIdleEnd = false;
td.Settings.Hidden = true;
td.Settings.UseUnifiedSchedulingEngine = true;
td.Settings.ExecutionTimeLimit = TimeSpan.Zero;
td.Settings.Priority = System.Diagnostics.ProcessPriorityClass.Normal;
td.Actions.Add(@"M:\NetworkConnectionManager\NetworkConnectionManager.EXE",
null, @"M:\NetworkConnectionManager\");
td.Triggers.Add(new LogonTrigger { UserId = @"JEFFL-PC\GUEST" });
ts.RootFolder.RegisterTaskDefinition("TaskName", td, TaskCreation.CreateOrUpdate,
@"JEFFL-PC\GUEST", null, TaskLogonType.InteractiveToken, null);
}
```

Commented Unassigned: Need to Set "RunOnlyIfLoggedOn" in Ver 2.0 [12031]

$
0
0
I've created a task with a trigger that starts a custom Windows Form application "At log on" of a specific user. In order for the task to succeed in running the application upon log on of the specific user, I must specify the specific user and their password when registering the task definition (ie: ts.RootFolder.RegisterTaskDefinition(taskName, td, TaskCreation.CreateOrUpdate...). I'm able to save/register the task, but the "Run whether user is logged on or not" option gets enabled under the "General > Security options" tab in the Task Manager. Thus, my application cannot start. When I manually change the Security option to "Run only when user is logged on" my application starts fine upon login. The problem is that I cannot set this option programmatically in ver 2.0 of the library.

In addition, I should not have to specify a password in the definition of the task if the "Run only when user is logged on" option is enabled because the user enters a password upon log on. When creating the task in the Task Scheduler manually, it does not prompt for a password.

How can I get this working so my application will start.
Comments: ** Comment from web user: jeffl012 **

It now works! Thanks for your help.

Closed Unassigned: Need to Set "RunOnlyIfLoggedOn" in Ver 2.0 [12031]

$
0
0
I've created a task with a trigger that starts a custom Windows Form application "At log on" of a specific user. In order for the task to succeed in running the application upon log on of the specific user, I must specify the specific user and their password when registering the task definition (ie: ts.RootFolder.RegisterTaskDefinition(taskName, td, TaskCreation.CreateOrUpdate...). I'm able to save/register the task, but the "Run whether user is logged on or not" option gets enabled under the "General > Security options" tab in the Task Manager. Thus, my application cannot start. When I manually change the Security option to "Run only when user is logged on" my application starts fine upon login. The problem is that I cannot set this option programmatically in ver 2.0 of the library.

In addition, I should not have to specify a password in the definition of the task if the "Run only when user is logged on" option is enabled because the user enters a password upon log on. When creating the task in the Task Scheduler manually, it does not prompt for a password.

How can I get this working so my application will start.

Closed Unassigned: Task Scheduler corrupted after using the managed wrapper to delete and re-create tasks [12042]

$
0
0
I am using the to build a Console app targeting .NET 4 that creates several tasks after deleting any old ones it created itself. Here is a link to the [Stack Overflow Question](http://stackoverflow.com/q/28938705/938668).

Task registration seems to succeed but the tasks do not launch and have somehow corrupted the Task Scheduler as follows:

![Task Manager Error](http://i.stack.imgur.com/J6edh.png)

The error dialog box in the image pops up six times which is how many tasks my app deleted then recreated. This happens when the Task Scheduler MMC Console if first launched and also when the House of Synergy folder is selected.

The code is a bit lengthy but necessary and ready to compile:

```
namespace TaskSchedulerHelper
{
using System;
using System.Diagnostics;
using System.Linq;
using System.Security.Principal;
using System.Windows.Forms;
using Microsoft.Win32.TaskScheduler;

internal static class Program
{
[STAThread]
private static void Main (string [] args)
{
var now = DateTime.Now;
var folderName = @"House of Synergy";
var taskNamePrefix = @"ShutDown Power Outage";
var applicationName = @"Task Scheduler Helper";

var times = new TimeSpan []
{
TimeSpan.FromHours(02), // 02:00 AM
TimeSpan.FromHours(06), // 06:00 AM
TimeSpan.FromHours(11), // 11:00 AM
TimeSpan.FromHours(15), // 03:00 PM
TimeSpan.FromHours(19), // 07:00 PM
TimeSpan.FromHours(23), // 11:00 PM
};

try
{
Console.Title = applicationName;

Console.WriteLine(applicationName);
Console.WriteLine();

// Uses the Task Scheduler Managed Wrapper
// from https://taskscheduler.codeplex.com/.
// Release: 2.3.0. Status: Stable.
// Date: Thu Dec 18, 2014 at 12:00 PM.
using (TaskService service = new TaskService())
{
var folder = service
.RootFolder
.SubFolders
.FirstOrDefault(f => (string.Compare(f.Name, folderName, StringComparison.InvariantCultureIgnoreCase) == 0));

if (folder == null) { folder = service.RootFolder.CreateFolder(folderName); }

var tasks = folder
.Tasks
//.Where(t => t.Name.StartsWith(taskNamePrefix, StringComparison.InvariantCultureIgnoreCase))
.ToList();

if (tasks.Any())
{
// Delete existing tasks.
Console.WriteLine("Deleting existing tasks.");
foreach (var task in tasks)
{
Console.Write(" - Deleting Task: {0}: ", task.Name);

try
{
task.Stop();

//task.Enabled = false; // Throws ComException: Element not found. (Exception from HRESULT: 0x80070490).
//Console.WriteLine(task.State); // Throws ComException: Element not found. (Exception from HRESULT: 0x80070490).

task.RegisterChanges();
folder.DeleteTask(task.Name, false);
task.Dispose();

Console.WriteLine("Done.");
}
catch (Exception exception)
{
Console.WriteLine("Exception: {0}.", exception);
}
}
}

Console.WriteLine();
Console.WriteLine("Creating new Tasks.");

foreach (var time in times)
{
var dateTimeNow = now.Date;
var definition = service.NewTask();
var dateTimeTrigger = now.Date.Add(time);
var taskName = taskNamePrefix + " " + dateTimeTrigger.ToString(@"hh-mm tt");

Console.Write(" - Creating Task: {0}: ", taskName);

try
{
definition.RegistrationInfo.Author = WindowsIdentity.GetCurrent().Name;
definition.RegistrationInfo.Date = DateTime.Now;
definition.RegistrationInfo.Description = "ShutDown event due to power outage at [" + dateTimeTrigger.ToLongTimeString() + "].";
definition.RegistrationInfo.Source = applicationName;
definition.RegistrationInfo.Version = new Version(1, 0, 0, 0);

definition.Settings.AllowDemandStart = true;
definition.Settings.AllowHardTerminate = false;
definition.Settings.Compatibility = TaskCompatibility.V2_1; // Windows 7 and above.
definition.Settings.DisallowStartIfOnBatteries = false;
definition.Settings.DisallowStartOnRemoteAppSession = false;
definition.Settings.Enabled = true;
definition.Settings.Hidden = false;
definition.Settings.MultipleInstances = TaskInstancesPolicy.IgnoreNew;
definition.Settings.Priority = ProcessPriorityClass.High;
definition.Settings.RestartCount = 10;
definition.Settings.RestartInterval = TimeSpan.FromMinutes(1);
definition.Settings.RunOnlyIfIdle = false;
definition.Settings.RunOnlyIfNetworkAvailable = false;
definition.Settings.StartWhenAvailable = true;
definition.Settings.StopIfGoingOnBatteries = false;
definition.Settings.UseUnifiedSchedulingEngine = true;
definition.Settings.WakeToRun = false;

definition.Actions.Add(new ShowMessageAction("Message Body", "Message Title"));
definition.Triggers.Add(new DailyTrigger() { StartBoundary = dateTimeTrigger.Subtract(TimeSpan.FromMinutes(10)), });

var task = folder.RegisterTaskDefinition(taskName, definition);

task.Enabled = true;
task.RegisterChanges();
// Always succeeds.
Console.WriteLine("Done.");

try
{
Console.WriteLine(" - Task Validation: ", task.Definition.Validate(throwException : true) ? "Succeeded." : "Failed.");
}
catch (Exception exception)
{
// Validation always fails.
Console.WriteLine(" - Task Validation Exception: {0}.", exception);
}
}
catch (Exception exception)
{
Console.WriteLine("Exception: {0}.", exception.Message);
}
}
}
}
catch (Exception exception)
{
Console.Write(exception);
}

Console.WriteLine();
Console.WriteLine();
Console.Write("Press any key to continue...");
Console.ReadKey(true);
}
}
}
```

New Post: trying to simply change tasks to disabled.

$
0
0
If the task already has been created, the Task.Enabled property does not require re-registration after. You should be able to simply call:
using (TaskService ts = new TaskService())
{
  Task t = ts.GetTask(taskName);
  if (t != null)
  {
    if (!t.Enabled)
    {
      t.Enabled = true;
    }
  }
}

New Post: Allows remote task creation when forcev1 = true ONLY

$
0
0
Thashiznets: V1 runs as a local process that acts on remote files. V2 runs as a COM+ service that passes messages back and forth via the network. This likely is the reason the firewall behaves differently between the two.

koushikc: I think this relates to my response above about how the two versions interact over the network. To dynamically determine which to use I would start with V2 and then try V1 if it fails. Since XP and Server 2003 are now out of support, it is a rarer case that a system will only support V1.

Updated Wiki: Examples

$
0
0

Examples Home Page

You can go to these pages for more sample code:
Below are some examples of how to use most of the functions of the library:
On all these examples, if you get an error on ambiguous references for 'Action', please preface it with 'Microsoft.Win32.TaskScheduler.Action'.

Using the editor
// Get the service on the local machineusing (TaskService ts = new TaskService())
{
   // Create a new taskconststring taskName = "Test";
   Task t = ts.AddTask(taskName, 
      new TimeTrigger() { StartBoundary = DateTime.Now + TimeSpan.FromHours(1),
         Enabled = false },
      new ExecAction("notepad.exe", "c:\\test.log", "C:\\"));

   // Edit task and re-register if user clicks Ok
   TaskEditDialog editorForm = new TaskEditDialog();
   editorForm.Editable = true;
   editorForm.RegisterTaskOnAccept = true;
   editorForm.Initialize(t);
   // ** The four lines above can be replaced by using the full constructor// TaskEditDialog editorForm = new TaskEditDialog(t, true, true);
   editorForm.ShowDialog();

   // Remove the task we just created
   ts.RootFolder.DeleteTask(taskName);
}

Simple example
// Get the service on the local machineusing (TaskService ts = new TaskService())
{
   // Create a new task definition and assign properties
   TaskDefinition td = ts.NewTask();
   td.RegistrationInfo.Description = "Does something";
   td.Principal.LogonType = TaskLogonType.InteractiveToken;

   // Add a trigger that will fire the task at this time every other day
   DailyTrigger dt = (DailyTrigger)td.Triggers.Add(new DailyTrigger(2));
   dt.Repetition.Duration = TimeSpan.FromHours(4);
   dt.Repetition.Interval = TimeSpan.FromHours(1);

   // Add a trigger that will fire every week on Friday
   td.Triggers.Add(new WeeklyTrigger { StartBoundary = DateTime.Today
      + TimeSpan.FromHours(2), DaysOfWeek = DaysOfTheWeek.Friday });

   // Add an action that will launch Notepad whenever the trigger fires
   td.Actions.Add(new ExecAction("notepad.exe", "c:\\test.log", null));

   // Register the task in the root folderconststring taskName = "Test";
   ts.RootFolder.RegisterTaskDefinition(taskName, td);

   // Retrieve the task, change the trigger and re-register it
   Task t = ts.GetTask(taskName);
   td = t.Definition;
   td.Triggers[0].StartBoundary = DateTime.Today + TimeSpan.FromDays(7);
   ts.RootFolder.RegisterTaskDefinition(taskName, td);

   // Remove the task we just created
   ts.RootFolder.DeleteTask(taskName);
}

Enumerate all tasks
void EnumAllTasks()
{
   using (TaskService ts = new TaskService())
      EnumFolderTasks(ts.RootFolder);
}

void EnumFolderTasks(TaskFolder fld)
{
   foreach (Task task in fld.Tasks)
      ActOnTask(task);
   foreach (TaskFolder sfld in fld.SubFolders)
      EnumFolderTasks(sfld);
}

void ActOnTask(Task t)
{
   // Do something interesting here
}

Complex example
string user = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
bool preWin7 = true;

// Get the service on the local machineusing (TaskService ts = new TaskService())
{
   // Display version and server state
   Version ver = ts.HighestSupportedVersion;
   bool newVer = (ver >= new Version(1, 2));
   Console.WriteLine("Highest version: " + ver);
   Console.WriteLine("Server: {0} ({1})", ts.TargetServer,
      ts.Connected ? "Connected" : "Disconnected");

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

   // Output all the tasks in the root folder with their triggers and actions
   TaskFolder tf = ts.RootFolder;
   Console.WriteLine("\nRoot folder tasks ({0}):", tf.Tasks.Count);
   foreach (Task t in tf.Tasks)
   {
      try
      {
         Console.WriteLine("+ {0}, {1} ({2})", t.Name,
            t.Definition.RegistrationInfo.Author, t.State);
         foreach (Trigger trg in t.Definition.Triggers)
            Console.WriteLine(" + {0}", trg);
         foreach (Action act in t.Definition.Actions)
            Console.WriteLine(" = {0}", act);
      }
      catch { }
   }

   // Output an enumeration of all folders under the root
   Console.WriteLine("\n***Checking folder enum***");
   TaskFolderCollection tfs = tf.SubFolders;
   if (tfs.Count > 0)
   {
      Console.WriteLine("\nSub folders:");
      try
      {
         foreach (TaskFolder sf in tfs)
            Console.WriteLine("+ {0}", sf.Path);
      }
      catch (Exception ex)
      {
         Console.WriteLine(ex.ToString());
      }
   }

   // Display information about the Microsoft folderif (newVer)
   {
      Console.WriteLine("\n***Checking folder retrieval***");
      try
      {
         TaskFolder sub = tf.SubFolders["Microsoft"];
         Console.WriteLine("\nSubfolder path: " + sub.Path);
      }
      catch (NotSupportedException) { }
      catch (Exception ex)
      {
         Console.WriteLine(ex.ToString());
      }
   }

   Console.WriteLine("\n***Checking task creation***");
   try
   {
      // Create a new task definition and assign properties
      TaskDefinition td = ts.NewTask();
      td.Data = "Your data";
      td.Principal.UserId = user;
      td.Principal.LogonType = TaskLogonType.InteractiveToken;
      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.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 = false;
      td.Settings.RunOnlyIfNetworkAvailable = false;
      td.Settings.StopIfGoingOnBatteries = true;
      if (newVer)
      {
         td.Principal.RunLevel = TaskRunLevel.Highest; //.LUA;
         td.RegistrationInfo.Source = "Test App";
         td.RegistrationInfo.URI = new Uri("test://app");
         td.RegistrationInfo.Version = new Version(0, 9);
         td.Settings.AllowDemandStart = true;
         td.Settings.AllowHardTerminate = true;
         td.Settings.Compatibility = TaskCompatibility.V2;
         td.Settings.DeleteExpiredTaskAfter = TimeSpan.FromMinutes(1);
         td.Settings.MultipleInstances = TaskInstancesPolicy.StopExisting;
         td.Settings.StartWhenAvailable = true;
         td.Settings.WakeToRun = false;
         td.Settings.RestartCount = 5;
         td.Settings.RestartInterval = TimeSpan.FromSeconds(100);
      }

      if (preWin7)
      {
         // Create a trigger that fires 5 minutes after the system is booted
         BootTrigger bTrigger = (BootTrigger)td.Triggers.Add(new BootTrigger { Enabled = false });
         if (newVer) bTrigger.Delay = TimeSpan.FromMinutes(5);
      }

      // Create a trigger that fires every other day randomly between 6:00 and 8:00 a.m.
      DailyTrigger dTrigger = (DailyTrigger)td.Triggers.Add(new DailyTrigger());
      dTrigger.StartBoundary = DateTime.Today + TimeSpan.FromHours(6);
      dTrigger.DaysInterval = 2;
      if (newVer) dTrigger.RandomDelay = TimeSpan.FromHours(2);

      if (newVer)
      {
         if (preWin7)
         {
            // Create a trigger that will fire on a system security event
            EventTrigger eTrigger = (EventTrigger)td.Triggers.Add(new EventTrigger());
            eTrigger.SetBasic("Security", "VSSAudit", 25);
            eTrigger.ValueQueries.Add("Name", "Value");
         }

         // Create a trigger that fires 5 minutes after this task is registered
         td.Triggers.Add(new RegistrationTrigger { Delay = TimeSpan.FromMinutes(5) });

         if (preWin7)
         {
            // Create triggers that fire after various system states are changed
            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 });
         }
      }

      // Create a trigger that fires when the system is idle
      td.Triggers.Add(new IdleTrigger());

      // Create a trigger that fires 15 minutes after the current user logs on and// then every 1000 seconds after that
      LogonTrigger lTrigger = (LogonTrigger)td.Triggers.Add(new LogonTrigger());
      if (newVer)
      {
         lTrigger.Delay = TimeSpan.FromMinutes(15);
         lTrigger.UserId = user;
         lTrigger.Repetition.Interval = TimeSpan.FromSeconds(1000);
      }

      // Create a trigger that fires on the 3rd, 6th, 10th, 18th, and last days of// July and November and stops triggering 90 days from now
      MonthlyTrigger mTrigger = (MonthlyTrigger)td.Triggers.Add(new MonthlyTrigger());
      mTrigger.DaysOfMonth = newint[] { 3, 6, 10, 18 };
      mTrigger.MonthsOfYear = MonthsOfTheYear.July | MonthsOfTheYear.November;
      if (newVer) mTrigger.RunOnLastDayOfMonth = true;
      mTrigger.EndBoundary = DateTime.Today + TimeSpan.FromDays(90);

      // Create a trigger that fires every day of the first and last week of// December and January
      MonthlyDOWTrigger mdTrigger = (MonthlyDOWTrigger)td.Triggers.Add(new MonthlyDOWTrigger());
      mdTrigger.DaysOfWeek = DaysOfTheWeek.AllDays;
      mdTrigger.MonthsOfYear = MonthsOfTheYear.January | MonthsOfTheYear.December;
      if (newVer) mdTrigger.RunOnLastWeekOfMonth = true;
      mdTrigger.WeeksOfMonth = WhichWeek.FirstWeek;

      // Create a trigger that fires 1 minute from now and then every 15 minutes for the// next 7 days.
      TimeTrigger tTrigger = (TimeTrigger)td.Triggers.Add(new TimeTrigger());
      tTrigger.StartBoundary = DateTime.Now + TimeSpan.FromMinutes(1);
      tTrigger.EndBoundary = DateTime.Today + TimeSpan.FromDays(7);
      if (newVer) tTrigger.ExecutionTimeLimit = TimeSpan.FromSeconds(15);
      if (newVer) tTrigger.Id = "Time test";
      tTrigger.Repetition.Duration = TimeSpan.FromMinutes(20);
      tTrigger.Repetition.Interval = TimeSpan.FromMinutes(15);
      tTrigger.Repetition.StopAtDurationEnd = true;

      // Create a trigger that fires every third week on Monday
      WeeklyTrigger wTrigger = (WeeklyTrigger)td.Triggers.Add(new WeeklyTrigger());
      wTrigger.DaysOfWeek = DaysOfTheWeek.Monday;
      wTrigger.WeeksInterval = 3;

      // Create an action which opens a log file in notepad
      td.Actions.Add(new ExecAction("notepad.exe", "c:\\test.log", null));
      if (newVer)
      {
         // Create an action which shows a message to the interactive user
         td.Actions.Add(new ShowMessageAction("Running Notepad", "Info"));
         // Create an action which sends an email
         td.Actions.Add(new EmailAction("Testing", "dahall@codeplex.com",
            "user@test.com", "You've got mail.", "mail.myisp.com"));
         // Create an action which loads a COM object and calls the ITaskHandler interface
         td.Actions.Add(new ComHandlerAction(new Guid("CE7D4428-8A77-4c5d-8A13-5CAB5D1EC734"),
            string.Empty));
      }

      // Register the task definition (saves it) in the security context of the interactive user
      tf.RegisterTaskDefinition("Test", td, TaskCreation.CreateOrUpdate, null, null,
         TaskLogonType.InteractiveToken, null);
   }
   catch (Exception ex)
   {
      Console.WriteLine(ex.ToString());
   }

   // Display information about the newly created task
   Task runningTask = tf.Tasks["Test"];
   Console.WriteLine("\nNew task will run at " + runningTask.NextRunTime);
   Console.WriteLine("\nNew task triggers:");
   for (int i = 0; i < runningTask.Definition.Triggers.Count; i++)
      Console.WriteLine("  {0}: {1}", i, runningTask.Definition.Triggers[i]);
   Console.WriteLine("\nNew task actions:");
   for (int i = 0; i < runningTask.Definition.Actions.Count; i++)
      Console.WriteLine("  {0}: {1}", i, runningTask.Definition.Actions[i]);

   // Remove the task we just created since this was just a test
   tf.DeleteTask("Test");
}

Fluent example
The library also exposes a Fluent syntax for accomplishing most functions. Below are a number of examples.
using (TaskService ts = new TaskService())
{
   ts.Execute("notepad.exe").WithArguments(@"c:\temp\music.txt").Once().Starting(2013, 11, 11, 11, 0, 0).RepeatingEvery(TimeSpan.FromMinutes(5)).AsTask("Test");

   ts.Execute("notepad.exe").Every(2).Days().Starting("12/25/2013 7:00pm").AsTask("Test");

   ts.Execute("notepad.exe").Every(3).Weeks().AsTask("Test");

   ts.Execute("notepad.exe").OnAll(DaysOfTheWeek.Monday).In(WhichWeek.FirstWeek).Of(MonthsOfTheYear.January).AsTask("Test");

   ts.Execute("notepad.exe").InTheMonthOf(MonthsOfTheYear.January).OnTheDays(1, 3, 5).AsTask("Test");

   ts.Execute("notepad.exe").OnBoot().AsTask("Test");

   ts.Execute("notepad.exe").OnIdle().AsTask("Test");

   ts.Execute("notepad.exe").OnStateChange(TaskSessionStateChangeType.ConsoleConnect).AsTask("Test");

   ts.Execute("notepad.exe").AtLogonOf("AMERICAS\\dahall").AsTask("Test");

   ts.Execute("notepad.exe").AtTaskRegistration().AsTask("Test");
}

Task history example
If you use the TaskEventLog constructor which specifies a remote machine, you will need to use impersonation to logon to an account with privileges to the remote machine before instantiating the TaskEventLog.
TaskEventLog log = new TaskEventLog(task.Path);
List<ListViewItem> c = new List<ListViewItem>(100);
foreach (TaskEvent item in log)
   c.Add(new ListViewItem(newstring[] { item.Level, item.TimeCreated.ToString(),
      item.EventId.ToString(), item.TaskCategory, item.OpCode, item.ActivityId.ToString() }));

Updated Wiki: Examples

$
0
0

Examples Home Page

You can go to these pages for more sample code:
Below are some examples of how to use most of the functions of the library:
On all these examples, if you get an error on ambiguous references for 'Action', please preface it with 'Microsoft.Win32.TaskScheduler.Action'.

Using the editor
// Get the service on the local machineusing (TaskService ts = new TaskService())
{
   // Create a new taskconststring taskName = "Test";
   Task t = ts.AddTask(taskName, 
      new TimeTrigger() { StartBoundary = DateTime.Now + TimeSpan.FromHours(1),
         Enabled = false },
      new ExecAction("notepad.exe", "c:\\test.log", "C:\\"));

   // Edit task and re-register if user clicks Ok
   TaskEditDialog editorForm = new TaskEditDialog();
   editorForm.Editable = true;
   editorForm.RegisterTaskOnAccept = true;
   editorForm.Initialize(t);
   // ** The four lines above can be replaced by using the full constructor// TaskEditDialog editorForm = new TaskEditDialog(t, true, true);
   editorForm.ShowDialog();

   // Remove the task we just created
   ts.RootFolder.DeleteTask(taskName);
}

Simple example
// Get the service on the local machineusing (TaskService ts = new TaskService())
{
   // Create a new task definition and assign properties
   TaskDefinition td = ts.NewTask();
   td.RegistrationInfo.Description = "Does something";
   td.Principal.LogonType = TaskLogonType.InteractiveToken;

   // Add a trigger that will fire the task at this time every other day
   DailyTrigger dt = (DailyTrigger)td.Triggers.Add(new DailyTrigger(2));
   dt.Repetition.Duration = TimeSpan.FromHours(4);
   dt.Repetition.Interval = TimeSpan.FromHours(1);

   // Add a trigger that will fire every week on Friday
   td.Triggers.Add(new WeeklyTrigger { StartBoundary = DateTime.Today
      + TimeSpan.FromHours(2), DaysOfWeek = DaysOfTheWeek.Friday });

   // Add an action that will launch Notepad whenever the trigger fires
   td.Actions.Add(new ExecAction("notepad.exe", "c:\\test.log", null));

   // Register the task in the root folderconststring taskName = "Test";
   ts.RootFolder.RegisterTaskDefinition(taskName, td);

   // Retrieve the task, change the trigger and re-register it
   Task t = ts.GetTask(taskName);
   td = t.Definition;
   td.Triggers[0].StartBoundary = DateTime.Today + TimeSpan.FromDays(7);
   ts.RootFolder.RegisterTaskDefinition(taskName, td);

   // Remove the task we just created
   ts.RootFolder.DeleteTask(taskName);
}

Enumerate all tasks
void EnumAllTasks()
{
   using (TaskService ts = new TaskService())
      EnumFolderTasks(ts.RootFolder);
}

void EnumFolderTasks(TaskFolder fld)
{
   foreach (Task task in fld.Tasks)
      ActOnTask(task);
   foreach (TaskFolder sfld in fld.SubFolders)
      EnumFolderTasks(sfld);
}

void ActOnTask(Task t)
{
   // Do something interesting here
}

Complex example
string user = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
bool preWin7 = true;

// Get the service on the local machineusing (TaskService ts = new TaskService())
{
   // Display version and server state
   Version ver = ts.HighestSupportedVersion;
   bool newVer = (ver >= new Version(1, 2));
   Console.WriteLine("Highest version: " + ver);
   Console.WriteLine("Server: {0} ({1})", ts.TargetServer,
      ts.Connected ? "Connected" : "Disconnected");

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

   // Output all the tasks in the root folder with their triggers and actions
   TaskFolder tf = ts.RootFolder;
   Console.WriteLine("\nRoot folder tasks ({0}):", tf.Tasks.Count);
   foreach (Task t in tf.Tasks)
   {
      try
      {
         Console.WriteLine("+ {0}, {1} ({2})", t.Name,
            t.Definition.RegistrationInfo.Author, t.State);
         foreach (Trigger trg in t.Definition.Triggers)
            Console.WriteLine(" + {0}", trg);
         foreach (Action act in t.Definition.Actions)
            Console.WriteLine(" = {0}", act);
      }
      catch { }
   }

   // Output an enumeration of all folders under the root
   Console.WriteLine("\n***Checking folder enum***");
   TaskFolderCollection tfs = tf.SubFolders;
   if (tfs.Count > 0)
   {
      Console.WriteLine("\nSub folders:");
      try
      {
         foreach (TaskFolder sf in tfs)
            Console.WriteLine("+ {0}", sf.Path);
      }
      catch (Exception ex)
      {
         Console.WriteLine(ex.ToString());
      }
   }

   // Display information about the Microsoft folderif (newVer)
   {
      Console.WriteLine("\n***Checking folder retrieval***");
      try
      {
         TaskFolder sub = tf.SubFolders["Microsoft"];
         Console.WriteLine("\nSubfolder path: " + sub.Path);
      }
      catch (NotSupportedException) { }
      catch (Exception ex)
      {
         Console.WriteLine(ex.ToString());
      }
   }

   Console.WriteLine("\n***Checking task creation***");
   try
   {
      // Create a new task definition and assign properties
      TaskDefinition td = ts.NewTask();
      td.Data = "Your data";
      td.Principal.UserId = user;
      td.Principal.LogonType = TaskLogonType.InteractiveToken;
      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.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 = false;
      td.Settings.RunOnlyIfNetworkAvailable = false;
      td.Settings.StopIfGoingOnBatteries = true;
      if (newVer)
      {
         td.Principal.RunLevel = TaskRunLevel.Highest; //.LUA;
         td.RegistrationInfo.Source = "Test App";
         td.RegistrationInfo.URI = new Uri("test://app");
         td.RegistrationInfo.Version = new Version(0, 9);
         td.Settings.AllowDemandStart = true;
         td.Settings.AllowHardTerminate = true;
         td.Settings.Compatibility = TaskCompatibility.V2;
         td.Settings.DeleteExpiredTaskAfter = TimeSpan.FromMinutes(1);
         td.Settings.MultipleInstances = TaskInstancesPolicy.StopExisting;
         td.Settings.StartWhenAvailable = true;
         td.Settings.WakeToRun = false;
         td.Settings.RestartCount = 5;
         td.Settings.RestartInterval = TimeSpan.FromSeconds(100);
      }

      if (preWin7)
      {
         // Create a trigger that fires 5 minutes after the system is booted
         BootTrigger bTrigger = (BootTrigger)td.Triggers.Add(new BootTrigger { Enabled = false });
         if (newVer) bTrigger.Delay = TimeSpan.FromMinutes(5);
      }

      // Create a trigger that fires every other day randomly between 6:00 and 8:00 a.m.
      DailyTrigger dTrigger = (DailyTrigger)td.Triggers.Add(new DailyTrigger());
      dTrigger.StartBoundary = DateTime.Today + TimeSpan.FromHours(6);
      dTrigger.DaysInterval = 2;
      if (newVer) dTrigger.RandomDelay = TimeSpan.FromHours(2);

      if (newVer)
      {
         if (preWin7)
         {
            // Create a trigger that will fire on a system security event
            EventTrigger eTrigger = (EventTrigger)td.Triggers.Add(new EventTrigger());
            eTrigger.SetBasic("Security", "VSSAudit", 25);
            eTrigger.ValueQueries.Add("Name", "Value");
         }

         // Create a trigger that fires 5 minutes after this task is registered
         td.Triggers.Add(new RegistrationTrigger { Delay = TimeSpan.FromMinutes(5) });

         if (preWin7)
         {
            // Create triggers that fire after various system states are changed
            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 });
         }
      }

      // Create a trigger that fires when the system is idle
      td.Triggers.Add(new IdleTrigger());

      // Create a trigger that fires 15 minutes after the current user logs on and// then every 1000 seconds after that
      LogonTrigger lTrigger = (LogonTrigger)td.Triggers.Add(new LogonTrigger());
      if (newVer)
      {
         lTrigger.Delay = TimeSpan.FromMinutes(15);
         lTrigger.UserId = user;
         lTrigger.Repetition.Interval = TimeSpan.FromSeconds(1000);
      }

      // Create a trigger that fires on the 3rd, 6th, 10th, 18th, and last days of// July and November and stops triggering 90 days from now
      MonthlyTrigger mTrigger = (MonthlyTrigger)td.Triggers.Add(new MonthlyTrigger());
      mTrigger.DaysOfMonth = newint[] { 3, 6, 10, 18 };
      mTrigger.MonthsOfYear = MonthsOfTheYear.July | MonthsOfTheYear.November;
      if (newVer) mTrigger.RunOnLastDayOfMonth = true;
      mTrigger.EndBoundary = DateTime.Today + TimeSpan.FromDays(90);

      // Create a trigger that fires every day of the first and last week of// December and January
      MonthlyDOWTrigger mdTrigger = (MonthlyDOWTrigger)td.Triggers.Add(new MonthlyDOWTrigger());
      mdTrigger.DaysOfWeek = DaysOfTheWeek.AllDays;
      mdTrigger.MonthsOfYear = MonthsOfTheYear.January | MonthsOfTheYear.December;
      if (newVer) mdTrigger.RunOnLastWeekOfMonth = true;
      mdTrigger.WeeksOfMonth = WhichWeek.FirstWeek;

      // Create a trigger that fires 1 minute from now and then every 15 minutes for the// next 7 days.
      TimeTrigger tTrigger = (TimeTrigger)td.Triggers.Add(new TimeTrigger());
      tTrigger.StartBoundary = DateTime.Now + TimeSpan.FromMinutes(1);
      tTrigger.EndBoundary = DateTime.Today + TimeSpan.FromDays(7);
      if (newVer) tTrigger.ExecutionTimeLimit = TimeSpan.FromSeconds(15);
      if (newVer) tTrigger.Id = "Time test";
      tTrigger.Repetition.Duration = TimeSpan.FromMinutes(20);
      tTrigger.Repetition.Interval = TimeSpan.FromMinutes(15);
      tTrigger.Repetition.StopAtDurationEnd = true;

      // Create a trigger that fires every third week on Monday
      WeeklyTrigger wTrigger = (WeeklyTrigger)td.Triggers.Add(new WeeklyTrigger());
      wTrigger.DaysOfWeek = DaysOfTheWeek.Monday;
      wTrigger.WeeksInterval = 3;

      // Create an action which opens a log file in notepad
      td.Actions.Add(new ExecAction("notepad.exe", "c:\\test.log", null));
      if (newVer)
      {
         // Create an action which shows a message to the interactive user
         td.Actions.Add(new ShowMessageAction("Running Notepad", "Info"));
         // Create an action which sends an email
         td.Actions.Add(new EmailAction("Testing", "dahall@codeplex.com",
            "user@test.com", "You've got mail.", "mail.myisp.com"));
         // Create an action which loads a COM object and calls the ITaskHandler// interface
         td.Actions.Add(new ComHandlerAction(new Guid("CE7D4428-8A77-4c5d-8A13-5CAB5D1EC734"),
            string.Empty));
      }

      // Register the task definition (saves it) in the security context of the// interactive user
      tf.RegisterTaskDefinition("Test", td, TaskCreation.CreateOrUpdate, null, null,
         TaskLogonType.InteractiveToken, null);
   }
   catch (Exception ex)
   {
      Console.WriteLine(ex.ToString());
   }

   // Display information about the newly created task
   Task runningTask = tf.Tasks["Test"];
   Console.WriteLine("\nNew task will run at " + runningTask.NextRunTime);
   Console.WriteLine("\nNew task triggers:");
   for (int i = 0; i < runningTask.Definition.Triggers.Count; i++)
      Console.WriteLine("  {0}: {1}", i, runningTask.Definition.Triggers[i]);
   Console.WriteLine("\nNew task actions:");
   for (int i = 0; i < runningTask.Definition.Actions.Count; i++)
      Console.WriteLine("  {0}: {1}", i, runningTask.Definition.Actions[i]);

   // Remove the task we just created since this was just a test
   tf.DeleteTask("Test");
}

Fluent example
The library also exposes a Fluent syntax for accomplishing most functions. Below are a number of examples.
using (TaskService ts = new TaskService())
{
   ts.Execute("notepad.exe").WithArguments(@"c:\temp\music.txt").Once().Starting(2013, 11, 11, 11, 0, 0).RepeatingEvery(TimeSpan.FromMinutes(5)).AsTask("Test");

   ts.Execute("notepad.exe").Every(2).Days().Starting("12/25/2013 7:00pm").AsTask("Test");

   ts.Execute("notepad.exe").Every(3).Weeks().AsTask("Test");

   ts.Execute("notepad.exe").OnAll(DaysOfTheWeek.Monday).In(WhichWeek.FirstWeek).Of(MonthsOfTheYear.January).AsTask("Test");

   ts.Execute("notepad.exe").InTheMonthOf(MonthsOfTheYear.January).OnTheDays(1, 3, 5).AsTask("Test");

   ts.Execute("notepad.exe").OnBoot().AsTask("Test");

   ts.Execute("notepad.exe").OnIdle().AsTask("Test");

   ts.Execute("notepad.exe").OnStateChange(TaskSessionStateChangeType.ConsoleConnect).AsTask("Test");

   ts.Execute("notepad.exe").AtLogonOf("AMERICAS\\dahall").AsTask("Test");

   ts.Execute("notepad.exe").AtTaskRegistration().AsTask("Test");
}

Task history example
If you use the TaskEventLog constructor which specifies a remote machine, you will need to use impersonation to logon to an account with privileges to the remote machine before instantiating the TaskEventLog.
TaskEventLog log = new TaskEventLog(task.Path);
List<ListViewItem> c = new List<ListViewItem>(100);
foreach (TaskEvent item in log)
   c.Add(new ListViewItem(newstring[] { item.Level, item.TimeCreated.ToString(),
      item.EventId.ToString(), item.TaskCategory, item.OpCode,
      item.ActivityId.ToString() }));

Created Unassigned: Task.Folder return null [12057]

$
0
0
It was reproduced only on Win Server 2008 Enterprise.
If you create a task in root folder the Task's field 'Folder' return null at first time.
That's happen because IRegisteredTask.Path returns the path without a slash at the beginning.
After the reloading data the issue disappear.
```
public TaskFolder Folder
{
get
{
if (v2Task == null)
return this.TaskService.RootFolder;

string path = v2Task.Path;
string parentPath = System.IO.Path.GetDirectoryName(path);
if (string.IsNullOrEmpty(parentPath))
return null;
return this.TaskService.GetFolder(parentPath);
}
}
```
(To get new task I use TaskEditorDialog.)
We can check v2Task.Path and add slash manually to the beginning. What do you think?
Also why this.TaskService.RootFolder return null when parentPath is empty. Maybe it should return this.TaskService.RootFolder?

Closed Unassigned: Task.Folder return null [12057]

$
0
0
It was reproduced only on Win Server 2008 Enterprise.
If you create a task in root folder the Task's field 'Folder' return null at first time.
That's happen because IRegisteredTask.Path returns the path without a slash at the beginning.
After the reloading data the issue disappear.
```
public TaskFolder Folder
{
get
{
if (v2Task == null)
return this.TaskService.RootFolder;

string path = v2Task.Path;
string parentPath = System.IO.Path.GetDirectoryName(path);
if (string.IsNullOrEmpty(parentPath))
return null;
return this.TaskService.GetFolder(parentPath);
}
}
```
(To get new task I use TaskEditorDialog.)
We can check v2Task.Path and add slash manually to the beginning. What do you think?
Also why this.TaskService.RootFolder return null when parentPath is empty. Maybe it should return this.TaskService.RootFolder?
Comments: Fixed in version 2.3.1. Thanks for finding this.
Viewing all 2206 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>