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

New Post: Quartz.Net

$
0
0
After a deeper review of the code and a few days of trying to refactor it to work with another scheduler engine, I've decided to abandon the effort. The pure amount of change I believe will introduce so many potential defects that I'm afraid it would be a step back for the project as a whole.

New Post: Quartz.Net

$
0
0
Hi, thanks for letting me know that. I guess it would require something to be designed from the ground up, maybe if I get the time I could look into it. Appreciate the feedback though, cheers

New Post: Access Denied while setting user to SYSTEM

$
0
0
On my development machine, I've tried changing the TaskDefinition to use the SYSTEM user account, which did not save (Windows 8.1 x64).

I switched to changing it during the RegisterTaskDefinition but get an Access Denied error. I am an administrator, and have tested it with UAC off, but it still won't take. (The path is fine and works) Here's the code:
_TaskService.RootFolder.RegisterTaskDefinition(HDC_FOLDER & "\" & ApplicationFolder() & "\" & Schedule.Id.ToString(), Schedule.TaskDefinition, TaskCreation.CreateOrUpdate, "SYSTEM", Nothing, TaskLogonType.ServiceAccount)

New Post: Long delay and high cpu usage constructing the edit dialog

$
0
0
I see long delays and high CPU utilization in the constructor for the TaskEditDialog. Has anyone else experienced this problem?

In some cases the dialog takes 15 to 30 seconds to return from the constructor using release code.

New Post: Access Denied while setting user to SYSTEM

$
0
0
Update ...

While my dev machine breaks while setting the user to System, a production machine does not. Oddest stuff. Anybody with any ideas?

New Post: Long delay and high cpu usage constructing the edit dialog

New Post: task launches as scheduled, but doesn't graphically show Notepad

$
0
0
I have some code which I use to schedule a task to launch notepad.exe after 2 minutes have elapsed.

The process seems to start fine, but the program doesn't show up in the UI.

Please help.

Here is the code:
        Dim ts As New TaskService
        Dim td As TaskDefinition = ts.NewTask

        Dim tf As TaskFolder = ts.RootFolder

        td.RegistrationInfo.Description = "Test action"
        td.Principal.LogonType = TaskLogonType.S4U
        td.Settings.DisallowStartIfOnBatteries = False
        td.Settings.Hidden = False
        td.Settings.Priority = System.Diagnostics.ProcessPriorityClass.Normal
        td.Settings.RunOnlyIfIdle = False
        td.Settings.RunOnlyIfNetworkAvailable = False
        td.Settings.StopIfGoingOnBatteries = False

        td.Principal.RunLevel = TaskRunLevel.Highest
        td.Settings.AllowDemandStart = True
        td.Settings.AllowHardTerminate = True
        td.Settings.Compatibility = TaskCompatibility.V2
        td.Settings.DeleteExpiredTaskAfter = TimeSpan.FromMinutes(1)
        td.Settings.StartWhenAvailable = True

        Dim tt As New TimeTrigger

        td.Triggers.Add(tt)

        tt.StartBoundary = DateTime.Now + TimeSpan.FromMinutes(2)
        tt.EndBoundary = DateTime.Now + TimeSpan.FromMinutes(2)

        tt.Repetition.StopAtDurationEnd = True

        tt.Enabled = True

        td.Actions.Add(New ExecAction("notepad.exe", "C:\test.txt"))

        Try

        tf.RegisterTaskDefinition("TestNewest", td, TaskCreation.CreateOrUpdate, My.User.Name, , TaskLogonType.S4U)


        Catch ex As Exception
            Debug.Print(ex.ToString())
        End Try

        Debug.Print("Task registered, will run at " + CStr(DateTime.Now + TimeSpan.FromMinutes(2)))

New Post: task launches as scheduled, but doesn't graphically show Notepad

$
0
0
To show an application running interactively, you must specify a LogonType of InteractiveToken. You can skip setting the td.Principal.LogonType property and just do it through the RegisterTaskDefinition method (e.g. RegisterTaskDefinition("TestNewest", td, TaskCreation.CreateOrUpdate, null, null, TaskLogonType.InteractiveToken)).

Created 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.

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

Created Unassigned: Inheritance security rules violated while overriding member [12037]

$
0
0
I'm trying to write a NAnt extension that uses this library but I get this exception on my first method that loads the taskscheduler objects.

System.TypeLoadException: Inheritance security rules violated while overriding member: 'Microsoft.Win32.TaskScheduler.TaskService.System.Runtime.Serialization.ISerializab
le.GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext)'. Security accessibility of the overriding method must mat
ch the security accessibility of the method being overriden.

I'm assuming this is related to NAnt dynamically loading the extension dll but I'm not sure how to get around it. Previously we were using the taskscheduler 1.0 library via NAnt without any issues.

New Post: NAnt extension getting Inheritance security rules violated while overriding member error

$
0
0
Hi, I originally posted this in the issues but now that I look at it I think it belongs in the discussion unless it becomes something we need a bug for. Unfortunately it doesn't look like I can remove my issue... Anyway...

I'm trying to write a NAnt extension that uses this library but I get this exception on my first method that loads the taskscheduler objects.

System.TypeLoadException: Inheritance security rules violated while overriding member: 'Microsoft.Win32.TaskScheduler.TaskService.System.Runtime.Serialization.ISerializab
le.GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext)'. Security accessibility of the overriding method must mat
ch the security accessibility of the method being overriden.

I'm assuming this is related to NAnt dynamically loading the extension dll but I'm not sure how to get around it. Previously we were using the taskscheduler 1.0 library via NAnt without any issues.
        public void test()
        {
            using (Microsoft.Win32.TaskScheduler.TaskService ts = new Microsoft.Win32.TaskScheduler.TaskService())
            {
                // Create a new task definition and assign properties
                Microsoft.Win32.TaskScheduler.TaskDefinition td = ts.NewTask();
                td.RegistrationInfo.Description = "Does something";

                // Create a trigger that will fire the task at this time every other day
                td.Triggers.Add(new Microsoft.Win32.TaskScheduler.DailyTrigger { DaysInterval = 2 });

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

                // Register the task in the root folder
                ts.RootFolder.RegisterTaskDefinition(@"Test", td);

            }
        }

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 **

Have you tried to set the TaskDefinition.Settings.RunOnlyIfLoggedOn property?

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 **

Yes, but it does not allow it under v2

Commented Unassigned: Inheritance security rules violated while overriding member [12037]

$
0
0
I'm trying to write a NAnt extension that uses this library but I get this exception on my first method that loads the taskscheduler objects.

System.TypeLoadException: Inheritance security rules violated while overriding member: 'Microsoft.Win32.TaskScheduler.TaskService.System.Runtime.Serialization.ISerializab
le.GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext)'. Security accessibility of the overriding method must mat
ch the security accessibility of the method being overriden.

I'm assuming this is related to NAnt dynamically loading the extension dll but I'm not sure how to get around it. Previously we were using the taskscheduler 1.0 library via NAnt without any issues.

```
public void test()
{
using (Microsoft.Win32.TaskScheduler.TaskService ts = new Microsoft.Win32.TaskScheduler.TaskService())
{
// Create a new task definition and assign properties
Microsoft.Win32.TaskScheduler.TaskDefinition td = ts.NewTask();
td.RegistrationInfo.Description = "Does something";

// Create a trigger that will fire the task at this time every other day
td.Triggers.Add(new Microsoft.Win32.TaskScheduler.DailyTrigger { DaysInterval = 2 });

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

// Register the task in the root folder
ts.RootFolder.RegisterTaskDefinition(@"Test", td);

}
}
```
Comments: ** Comment from web user: dahall **

I believe this is related to a change in the security model for .NET 4.0. I have added the SecurityCritical attribute to the method in your exception and have posted a .NET 4.0 build under attachments. Please check it and confirm it resolves your issue and then I'll get it added into the next release (2.3.1).

New Post: NAnt extension getting Inheritance security rules violated while overriding member error

$
0
0
I believe this is related to a change in the security model for .NET 4.0. I have added the SecurityCritical attribute to the method in your exception and have posted a .NET 4.0 build under the issue you posted. Please check it and confirm it resolves your issue and then I'll get it added into the next release (2.3.1).

Commented Unassigned: Inheritance security rules violated while overriding member [12037]

$
0
0
I'm trying to write a NAnt extension that uses this library but I get this exception on my first method that loads the taskscheduler objects.

System.TypeLoadException: Inheritance security rules violated while overriding member: 'Microsoft.Win32.TaskScheduler.TaskService.System.Runtime.Serialization.ISerializab
le.GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext)'. Security accessibility of the overriding method must mat
ch the security accessibility of the method being overriden.

I'm assuming this is related to NAnt dynamically loading the extension dll but I'm not sure how to get around it. Previously we were using the taskscheduler 1.0 library via NAnt without any issues.

```
public void test()
{
using (Microsoft.Win32.TaskScheduler.TaskService ts = new Microsoft.Win32.TaskScheduler.TaskService())
{
// Create a new task definition and assign properties
Microsoft.Win32.TaskScheduler.TaskDefinition td = ts.NewTask();
td.RegistrationInfo.Description = "Does something";

// Create a trigger that will fire the task at this time every other day
td.Triggers.Add(new Microsoft.Win32.TaskScheduler.DailyTrigger { DaysInterval = 2 });

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

// Register the task in the root folder
ts.RootFolder.RegisterTaskDefinition(@"Test", td);

}
}
```
Comments: ** Comment from web user: digdug **

Thanks for the prompt response. Unfortunately I'm still getting the same error.

Additional information: Inheritance security rules violated while overriding member: 'Microsoft.Win32.TaskScheduler.TaskService.System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext)'. Security accessibility of the overriding method must match the security accessibility of the method being overriden.

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 **

My mistake. To get the effect of that property, you will need to register the task using a TaskLogonType of InteractiveToken or InteractiveTokenOrPassword. The first takes no username or password and the second requires both. Under v2, the logon type determines the state of that checkbox.

New Post: Windows 10 Support

$
0
0
Do you have a timeline for Windows 10 support?

The Editor is pretty broken due to this function. You could support the back level versions of the scheduler with an else for ....Major == 10.

internal static int GetOSLibraryMinorVersion()
    {
        if (Environment.OSVersion.Version.Major == 6)
        {
            switch (Environment.OSVersion.Version.Minor)
            {
                case 0:
                    return 2;
                case 1:
                    return 3;
                default:
                    return 4;
            }
        }
        return 1;
    }

New Post: How to Query historical task log with any conditions and and how to list instances of a task

$
0
0
1. How to query historical task log with specified condition like “time create”, “correlation ID”..

Genertal code
public static void SchedulerHistory(string schedulerName)
{            
            using (TaskService ts = new TaskService())
            {
                Microsoft.Win32.TaskScheduler.Task task = ts.GetTask(schedulerName);
                TaskEventLog eventLogs = new TaskEventLog(task.Path);
                foreach (TaskEvent log in eventLogs)
                {                    
                    string level = log.Level;
                    DateTime? dateTime = log.TimeCreated;
                    int eventId = log.EventId;
                    string taskCategory = log.TaskCategory;
                    string code = log.OpCode;
                }
            }
}   
My code need to apply condition to query
1.I need to apply correlation ID as criteria to query.
2.I get correlationID from RunningTaskCollection of a task and use it to query history task later
Microsoft.Win32.TaskScheduler.Task task = GetTask(groupName);
// GetTask is my method that detail of this  have been written as you.
RunningTaskCollection runningTaskList = task.GetInstances();


    for (int i = 0; i < runningTaskList.Count; i++){

        Guid correlationID = runningTaskList[i].InstanceGuid;
 _      List<TaskEvent> list = (new TaskEventLog(path)).Where(lg => lg.ActivityId == correlationID).OrderBy(log => log.TimeCreated).Take(1).ToList();_
                foreach (TaskEvent log in list)
                {      

              // do something as my business logic              
                    string level = log.Level;
                    DateTime? dateTime = log.TimeCreated;
                    int eventId = log.EventId;
                    string taskCategory = log.TaskCategory;
                    string code = log.OpCode;
                }
}
My business logic is that I need to get first record of each transaction in history task with either correlationID or TimeCreated for doing something later as figure below.

As per my code, I take correlationID as condition, I am not sure whether this code is correct and efficient statement for getting task with LINQ .
It seem pretty slow because this statement has to load all records in history with “(new TaskEventLog(path))” and then using LINQ to query as conditin later.

Image


2. How to list all instances of each specified task name not only running instance but also finished instance (completed and error instance)
As far as I know, I can list only running instance from a task with below code.
Microsoft.Win32.TaskScheduler.Task task = GetTask(groupName);
// GetTask is my method that detail of this  have been written as you.
RunningTaskCollection runningTaskList = task.GetInstances();
However , I would like to get every instance of task both running and history.
Are there any ways to do this besides getting from historical task?.

Created 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);
}
}
}
```
Viewing all 2206 articles
Browse latest View live




Latest Images