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

Commented 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);
}
}
}
```
Comments: ** Comment from web user: dahall **

Thank you for the detail. I will try to get to this today, but have to travel for my real job this week and may not get to resolve this until Friday. At first glance, you are unnecessarily calling RegisterChanges in two places. Also, instead of enumerating folders, you should be able to just call
```
if (RootFolder.SubFolders.Exists(folderName))
folder = RootFolder.SubFolders[folderName];
else
folder = RootFolder.CreateFolder(folderName);
```
to get a reference to the folder. This will come back null if the folder doesn't exist.

You may also want to try extracting the task names to a list and then using those names to delete the tasks instead of holding on to the Task references.


Viewing all articles
Browse latest Browse all 2206

Trending Articles



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