New Post: Quartz.Net
New Post: Quartz.Net
New Post: Access Denied while setting user to SYSTEM
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
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
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
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
Created Unassigned: Need to Set "RunOnlyIfLoggedOn" in Ver 2.0 [12031]
How can I get this working so my application will start.
Created Unassigned: Inheritance security rules violated while overriding member [12037]
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
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]
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]
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]
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
Commented Unassigned: Inheritance security rules violated while overriding member [12037]
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]
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
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
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 query1.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.
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]
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);
}
}
}
```