Coder Social home page Coder Social logo

dahall / taskscheduler Goto Github PK

View Code? Open in Web Editor NEW
1.2K 41.0 186.0 142.45 MB

Provides a .NET wrapper for the Windows Task Scheduler. It aggregates the multiple versions, provides an editor and allows for localization.

License: MIT License

C# 99.89% Visual Basic .NET 0.11%
dotnet task-scheduler csharp controls component winforms windows

taskscheduler's Introduction

Task Scheduler Managed Wrapper

Version Downloads Build status

The original .NET wrapper for the Windows Task Scheduler that aggregates the multiple versions and provides localized controls for editing.

Quick Links

Installation

This project's assemblies are available via NuGet or manually from the .zip files in the Releases section.

Link Package Name Description
NuGet TaskScheduler Main Library
NuGet TaskSchedulerEditor UI Library

You can also find prerelease NuGet pacakges on the project's AppVeyor NuGet feed.

Once referenced by your project, all classes can be found in the Microsoft.Win32.TaskScheduler namespace.

Project Components

Main Library

Microsoft introduced version 2.0 (internally version 1.2) with a completely new object model with Windows Vista. The managed assembly closely resembles the new object model, but allows the 1.0 (internally version 1.1) COM objects to be manipulated. It will automatically choose the most recent version of the library found on the host system (up through 1.4). Core features include:

  • Separate, functionally identical, libraries for .NET 2.0, 3.5, 4.0, 4.52, 5.0, 6.0, .NET Standard 2.0, .NET Core 2.0, 2.1, 3.0, 3.1.
  • Unlike the base COM libraries, this wrapper helps to create and view tasks up and down stream.
  • Written in C#, but works with any .NET language including scripting languages (e.g. PowerShell).
  • Supports all V2 native properties, even under V1 systems.
  • Maintain EmailAction and ShowMessageAction using PowerShell scripts for systems after Win8 where these actions have been deprecated.
  • Supports all action types (not just ExecAction) on V1 systems (XP/WS2003) and earlier (if PowerShell is installed).
  • Supports multiple actions on V1 systems (XP/WS2003). Native library only supports a single action.
  • Supports serialization to XML for both 1.0 and 2.0 tasks (base library only supports 2.0)
  • Supports task validation for targeted version.
  • Supports secure task reading and maintenance.
  • Fluent methods for task creation.
  • Cron syntax for trigger creation.
  • Supports reading "custom" triggers under Win8 and later.
  • Numerous work-arounds and checks to compensate for base library shortcomings.

The currently supported localizations include: English, Spanish, Italian, French, Chinese (Simplified), German, Polish and Russian. Others localizations can be added upon request, especially if you're willing to help with translations.

The project is based on work the originator started in January 2002 with the 1.0 library that is currently hosted on CodeProject.

UI Library

A second library includes localized and localizable GUI editors and a wizard for tasks which mimic the ones in Vista and later and adds optional pages for new properties. Following is the list of available UI controls:

  • Task editor dialog and tabbed control which mimics system editor (TaskEditDialog)
  • Task editor dialog using newer UI scheme (TaskOptionsEditor)
  • Task creation wizard which mimics system Basic editor
  • Action editor dialog
  • Trigger editor dialog
  • Event viewer dialog
  • Task / task folder selection dialog
  • Task history viewer
  • Task run-times viewer
  • Task service connection dialog
  • Simplified classes for pulling events from the system event log.
  • A DropDownCheckList control that is very useful for selecting flag type enumerations.
  • A FullDateTimePicker control which allows both date and time selection in a single control.
  • A CredentialsDialog class for prompting for a password which wraps the Windows API.

Sample Code

There is a help file included with the download that provides an overview of the various classes. There are numerous examples under the "Documentation" tab.

You can perform a number of actions in a single line of code:

// Run a program every day on the local machine
TaskService.Instance.AddTask("Test", QuickTriggerType.Daily, "myprogram.exe", "-a arg");

// Run a custom COM handler on the last day of every month
TaskService.Instance.AddTask("Test", new MonthlyTrigger { RunOnLastDayOfMonth = true }, 
    new ComHandlerAction(new Guid("{CE7D4428-8A77-4c5d-8A13-5CAB5D1EC734}")));

For many more options, use the library classes to build a complex task. Below is a brief example of how to use the library from C#.

using System;
using Microsoft.Win32.TaskScheduler;

class Program
{
   static void Main(string[] args)
   {
      // Get the service on the remote machine
      using (TaskService ts = new TaskService(@"\\RemoteServer", "username", "domain", "password"))
      {
         // Create a new task definition and assign properties
         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 DailyTrigger { DaysInterval = 2 });

         // Create 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 folder.
         // (Use the username here to ensure remote registration works.)
         ts.RootFolder.RegisterTaskDefinition(@"Test", td, TaskCreation.CreateOrUpdate, "username");
      }
   }
}

For extended examples on how to the use the library, look in the source code area or look at the Examples Page. The library closely follows the Task Scheduler 2.0 Scripting classes. Microsoft has some examples on Microsoft Docs around it that may further help you understand how to use this library.


This project appreciatively uses:

ReSharper from JetBrains ReSharper from JetBrains

Sandcastle Help File Builder Sandcastle Help File Builder

taskscheduler's People

Contributors

chrisdent-de avatar dahall avatar damirainullin avatar filipnavara avatar indigo744 avatar pashcovich avatar spirifoxy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

taskscheduler's Issues

DeleteExpiredTaskAfter error

I am trying to create a task that runs a cmd and after it's done (+ 5 minutes) it deletes itself. If I set up the task without td.Settings.DeleteExpiredTaskAfter and wihtout tt.EndBoundary. It works just fine. Do you have any ideas what I did wrong or what am I missing?
The error I'm getting is "(35,4):EndBoundary:".

Here is my function

private void createTask(DateTime dateAndTime, string username, string groupName, string computer_name)
{
	using (TaskService ts = new TaskService(computer_name))
	{
		TaskDefinition td = ts.NewTask();

		TimeTrigger tt = new TimeTrigger();
		tt.StartBoundary = dateAndTime;
		tt.EndBoundary = dateAndTime + TimeSpan.FromMinutes(5);
		
		td.Settings.StartWhenAvailable = true;
		td.Settings.Hidden = true;
		td.Settings.ExecutionTimeLimit = TimeSpan.FromMinutes(10);
		td.Settings.DeleteExpiredTaskAfter = TimeSpan.FromMinutes(1);
		td.Settings.DisallowStartIfOnBatteries = false;

		string parametr = "/c net localgroup " + groupName + " /delete " + username;
		td.Actions.Add(new ExecAction("cmd.exe",parametr, null));

		ts.RootFolder.RegisterTaskDefinition(@"Automatic Membership Validation", td,
		TaskCreation.CreateOrUpdate,"SYSTEM",null,TaskLogonType.ServiceAccount);
	}
}

This is how I call the function

createTask(dateTimePicker1.Value, "testuser", "Administrators", "testcomputer");

In all cases dateTimePicker is set-up like this:

dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = "dd'.'MM.yyyy - HH':'mm";

Code to run when idle

How can I use this to make a program run when no input is made for X amount of time?

In Task editor, selecting a COM object from the list injects the name into the text field, not the GUID

The selected COM object has its name inserted into the text field, instead of the GUID, this causes a validation error in ComHandlerActionUI.comCLSIDText_Validating

  1. Edit Task
  2. Select Add New Action
  3. Select Custom handler
  4. Select the Browse button, and "Lookup CLSID"
  5. Select a COM object
  6. Notice the name is returned, instead of the GUID, this causes a red validation error to appear.
    image

The error is "Invalid GUID for CLSID"

This is the same class I selected in issue #27 .

In a slightly related issue, if you select "Manually Enter CLSID", the OK button is not enabled unless you already tried to select a COM server in the browse list.

How to set the Task Scheduler to repeat indefinitely?

After referring to samples "https://github.com/dahall/TaskScheduler/wiki" and the api documentation for RepetitionPattern class "https://dahall.github.io/TaskScheduler/html/T_Microsoft_Win32_TaskScheduler_RepetitionPattern.htm". I'm not able to find how to set the repetitive duration to run "indefinitely". Is it possible to create a task scheduler with the repetition duration is indefinitely?

I have also tried assigning TimeSpan.MaxValue to trigger.Repetition.Duration, but it seems not possible with the application end up throwing exception.

TaskDefinition.Principal.UserId in Windows 2016

TaskScheduler 2.6.3

Hello, I setup a scheduled task to be run by a user in Windows 2016, when I look at that task via the TaskScheduler library, the TaskDefinition.Principal.UserId for this task is an empty string. If I look at the raw XML for the task:

<Principals>
	<Principal id="Author">      
		<UserId>S-1-5-21-#########-##########-##########-####</UserId>      
		<LogonType>Password</LogonType>      
		<RunLevel>LeastPrivilege</RunLevel>    
	</Principal>  
</Principals>  

I can see the SID instead of the user id which is defined as a possibility (https://msdn.microsoft.com/en-us/library/cc248346.aspx). However, I don't see that SID in any of the fields exposed in the TaskPrincipal object (or anywhere else in the Task object).

Should I expect it to be, or am I possibly doing something wrong? I mentioned Windows 2016, but I don't know if this is really specific to Windows 2016, it just is the only OS I've run into this on. Thanks!

Unable to Register a task with [COMException (0x80041318): (44,4):Task:]

Hello,
I am trying to register a task through a web app deployed to an IIS server (Windows Server 2012 R2).
The task is to be run one time only. Action is set to be opening the notepad for testing purpose.

using (TaskService ts = new TaskService())
{
TaskDefinition td = ts.NewTask();
td.RegistrationInfo.Description = "Open notepad";
td.Principal.LogonType = TaskLogonType.InteractiveToken;
DateTime time = Convert.ToDateTime(txttime.Text);
DateTime date = Convert.ToDateTime(txtdate.Text);
DateTime send_time = date.Add(time.TimeOfDay);
td.Triggers.Add(new TimeTrigger(send_time));
td.Actions.Add(new ExecAction("notepad.exe", null, null));
//td.Principal.RunLevel = TaskRunLevel.Highest;
TaskFolder tf = ts.GetFolder("\\Microsoft\\Windows\\Notepad");
tf.RegisterTaskDefinition(taskName, td);
}

Use the official one by debugging in localhost is fine but runs into the same error when deployed to server. I have searched over the code and I have no idea what required element or attribute I have missed. Use the wrapper by debugging in localhost also run to an access denied error no matter with or without an admin account.

I am wondering if that is a problem of account permission but adding an account in the Task service config and task registration part only bring more errors like access denied or something like:

Attempted to access an unloaded appdomain. (Exception from HRESULT: 0x80131014)

The tutorial on Task Security provides several approaches but I have tried all possibilities:

  • local computer (no account vs admin account)
  • remote server (NETWORK SERVICE & admin account & no account)
  • interactive token vs account password
  • system account
  • admin right of setting the highest property

I have been struggling in the task registration...
Is it better to get an admin account to get it work ? resulting in a bunch or access error though :(
Thanks in advance for any advice.

Update:
The missing requirement issue was solved by changing the time trigger to
td.Triggers.Add(new TimeTrigger() { StartBoundary = send_time });
locally but the problem is still there to make it work on remote server.
Thanks.

Trying to connect to a remote machine but I always have access denied error

Hello,
im trying to connect to a remote machine to get all task and im using:

using (TaskService ts = new TaskService(computer,user,domain,password)) { EnumFolderTasks(ts.RootFolder); }
but i have this error:
The request is not supported. (Exception from HRESULT: 0x80070032)
or access denied error, but the credentials is right.

Can anyone help me?
Thanks

.NET Framework NGEN v4.0.30319 "error"

Hello,

ich want to connect from a 2016 Server to a win10 Client (remote) and read all Tasks.

I used:

var x = new TaskService($@"\{Host}", _username, _domain, _password);
....

i got the error:
The current version of the native library (1.5) does not support the original or minimum version of the ".NET Framework NGEN v4.0.30319" task (1.6/1.6)

does anyone have a tip for me?

Thanks

Repetitive (One Time Trigger) Schedule does not run on the last/final "Next Run Time"

I have an issue where it only occurred on One Time trigger with repetitive configured. It doesn't run on the last/final "Next Run Time" and it only happens when the task is created from code.

For example:
When i set it to start the schedule on 10:00:00 AM and to repeat the task every 1 minute for a duration of 2 minutes. The task executed at 10:00:00 AM & 10:01:00 AM, but at 10:02:00 AM did not get executed even though the "Next Run Time" did specify to run at 10:02:00 AM in task scheduler window.

Did not find anything on history tab and the event log. There is no error and it did not stamp any information for 10:02:00 AM.

I have tried to manually create the task through the task scheduler window and it doesn't have this problem.

Version tried on "2.5.21" & "2.6.3".
Tested on Windows Server 2016 & Windows Server 2012 R2.

`using (var taskService = new TaskService())
{
var taskSchedulerFolder = @"Tasks Folder\CustomSchedulerProcessor";

var taskDefinition = taskService.NewTask();
var registrationInfo = taskDefinition.RegistrationInfo;
registrationInfo.Date = DateTime.Now;

var settings = taskDefinition.Settings;
settings.StartWhenAvailable = true;
settings.AllowDemandStart = false;
settings.MultipleInstances = TaskInstancesPolicy.IgnoreNew;
settings.DisallowStartIfOnBatteries = false;
settings.StopIfGoingOnBatteries = false;

var trigger = new TimeTrigger();
trigger.StartBoundary = DateTime.Now.AddSeconds(5);
trigger.Repetition.Interval = new TimeSpan(0, 1, 0);
trigger.Repetition.Duration = new TimeSpan(0, 2, 0);
trigger.Repetition.StopAtDurationEnd = false;

using (trigger)
{
    taskDefinition.Triggers.Add(trigger);

    using (var execAction = new ExecAction(@"E:\OneTimeConsole.exe"))
    {
        taskDefinition.Actions.Add(execAction);

        var logonUser = string.Empty;

        using (var currentWindowsIdentity = WindowsIdentity.GetCurrent())
        {
            logonUser = (new WindowsPrincipal(currentWindowsIdentity)).Identity.Name;
        }

        taskDefinition.RegistrationInfo.Author = logonUser;

        taskService.GetFolder(taskSchedulerFolder).RegisterTaskDefinition(Guid.NewGuid().ToString().Replace("-", string.Empty), taskDefinition, TaskCreation.Create, logonUser, logonType: TaskLogonType.InteractiveToken);
    }
}

}`

Add task to folder using TaskEditDialog

Hi,
what is the right way to add new task to specific folder using dialog? I use such code to add to root folder, tried to specify editorForm.TaskFolder, but task still created in RootFolder.

Using ts As New TaskService()
Dim td As TaskDefinition = ts.NewTask()
Dim f As TaskFolder = ts.GetFolder(strFolder)
td.Actions.Add(strExeFilename)
Dim editorForm As New TaskEditDialog(ts, td, True, True)
editorForm.ShowDialog()

Or, perhaps it is possible to move task to other folder?

Alex

TaskEditDialog seems to reset the "user account" setting

I am trying to create a task that runs under the "SYSTEM" user account, and I am able to do so using the RegisterTaskDefinition as such: ts.RootFolder.RegisterTaskDefinition(taskName, td, TaskCreation.CreateOrUpdate, "SYSTEM", null, TaskLogonType.ServiceAccount). If I manually open up Windows Task Manager, I can see that it is still set to run as "SYSTEM."

However, if I create a TaskEditDialog and call ShowDialog for that task, the user property resets to the logged on user, rather than "SYSTEM." I can see my user name in the "When running the task, use the following user account" field, and when I click OK, it updates the Task to use my user name. However, if I click "Cancel," the Task (as visible in Windows Task Scheduler) still reflects the original user of "SYSTEM."

It seems as though the TaskEditDialog is intentionally resetting the user property on the Task to the currently-logged in user, disregarding the user that may have been purposefully set prior to the ShowDialog call.

Windows 10 Task Scheduler Security

This isn't strictly related to your library, but perhaps you or other users of this library have run into and know of a solution. It seems under Windows 10, it's no longer possible for an ordinary user to view tasks created by other users or administrators. Under previous versions of Windows, it was possible to modify the ACL's on C:\Windows\System32\Tasks to allow lower privileged users to read and/or modify tasks that they wouldn't otherwise be able to access.

Does anyone know a way around this Windows 10 limitation?

Cron expression evaluation is incomplete

Granted, the comments in the code warn of this, but some basic expressions seem to have incorrect interpretations --
*/15 * * * * should be interpreted as "every 15 minutes" but returns a not-implemented exception.
likewise for alternate expressions with the same meaning: 0-59/15 * * * * and 0,15,30,45 * * * *
Reporting this as a bug as this expression, 0/15 * * * * which should mean every fifteen minutes starting at midnight is instead interpreted as "every hour, at midnight."
Another issue is with commas, i.e. 0 0,12 * * * (midnight & noon daily) which seem to throw the whole interpreter out the window. A job is created with no trigger at all.

In Task Editor, Marshal.ReleaseComObject throws an ArgumentException when called on a .NET COM class

I created a COM server in C#, but when I try to select my COM class as a custom action in the Task editor, I get an exception:

System.ArgumentException occurred
  HResult=0x80070057
  Message=The object's type must be __ComObject or derived from __ComObject.
Parameter name: o
  Source=mscorlib
  StackTrace:
   at System.Runtime.InteropServices.Marshal.ReleaseComObject(Object o)
   at Microsoft.Win32.TaskScheduler.ComObjectSelectionDialog.SupportsInterface(Guid clsid, Guid iGuid)
   at Microsoft.Win32.TaskScheduler.ComObjectSelectionDialog.listView1_ItemSelectionChanged(Object sender, ListViewItemSelectionChangedEventArgs e)
   at System.Windows.Forms.ListView.OnItemSelectionChanged(ListViewItemSelectionChangedEventArgs e)
   at System.Windows.Forms.ListView.WmReflectNotify(Message& m)
   at System.Windows.Forms.ListView.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

Here's the class I created:

using Microsoft.Win32.TaskScheduler;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace Scheduler
{
    [ComVisible(true)]  // This is mandatory.
    [Guid("4945B34B-1B63-4a58-B5FE-9627FEFAEA9D")]
    [InterfaceType(ComInterfaceType.InterfaceIsDual)]
    public interface ITaskRunner
    {
    }

    [Guid("FA40C9BB-410C-46D2-AEC9-8F7D952B3E91")]
    [ClassInterface(ClassInterfaceType.AutoDispatch)]
    [ComVisible(true)]
    public class TaskRunner : ITaskHandler
    {
        public void Start(object pHandlerServices, string data)
        {
            throw new NotImplementedException();
        }

        public void Stop(out int pRetCode)
        {
            throw new NotImplementedException();
        }

        public void Pause()
        {
            throw new NotImplementedException();
        }

        public void Resume()
        {
            throw new NotImplementedException();
        }
    }
}

If I remove the Marshal.ReleaseComObject call in SupportsInterface, I can select it fine.
I noticed this with other COM servers on my machine (when randomly selecting), not just mine.

Settings.RunOnlyIfLoggedOn = False not working with Task Scheduler 1.0

If OSVersionInfo.Name.Equals("Windows Server 2003") Or OSVersionInfo.Name.Equals("Windows XP") Then 'V1: Win XP, Win 2003 Server
            Using ts As New TaskService()
                ' Create a new task definition and assign properties
                Dim td As TaskDefinition = ts.NewTask
                td.RegistrationInfo.Description = "Something"
                td.RegistrationInfo.Author = "Someone"

                td.Settings.RunOnlyIfIdle = False
                td.Settings.DisallowStartIfOnBatteries = False
                td.Settings.StopIfGoingOnBatteries = False
                td.Settings.WakeToRun = True
                td.Settings.RunOnlyIfNetworkAvailable = True
                td.Settings.RunOnlyIfLoggedOn = False

                Dim wt As New WeeklyTrigger()
                wt.StartBoundary = Date.Today.AddDays(-1) + TimeSpan.FromHours(horario.hora) + TimeSpan.FromMinutes(horario.minuto) 'Inicia hoy a la hora programada
                Dim diasArray() As String = dias.Split(",")
                wt.DaysOfWeek = ConvertArrayToDayOfWeek(diasArray)
                wt.WeeksInterval = 1
                td.Triggers.Add(wt)

                td.Actions.Add(New ExecAction(ruta, argumento))

                ts.RootFolder.RegisterTaskDefinition("Some_Task",
                                                     td)
            End Using
End If

err_task

Localization to Russian

Hello!
First of all let me thank you for such an amazing piece of work.
And I'm sorry for opening a new issue due to my only personal small need.
So would you mind helping me with localization to Russian language?
What exactly I need to be localized is TaskEditDialog and all information related to trigger descriptions.

BUT! There is one more problem. I am not able to build this project on my own because of lower VS version than required.
Is there any chance of you providing me with rebuilt dll after I prepare aforementioned translations?

Cannot modify task security descriptor

I need to change task security descriptor (add permission for authenticated user), so what I do on Windows 10:

  1. Create a simple task in Scheduled Task Windows snap-in using "Create Basic task" wizard. It's really "simple" - I use word "simple" for all mandatory text fields and don't modify task triggers.
    Attached it's xml just for the case simple.xml.txt

  2. Try to change task security descriptor (I inserted this snippet at the end of ShortTest function)

t = ts.GetTask("simple");
var sec = t.GetAccessControl();
var sid = new System.Security.Principal.SecurityIdentifier(System.Security.Principal.WellKnownSidType.AuthenticatedUserSid, null);
var rule = new TaskAccessRule(sid, TaskRights.Read, System.Security.AccessControl.AccessControlType.Allow);
sec.AddAccessRule(rule);
t.SetAccessControl(sec);
  1. On statement sec.AddAccessRule I get InvalidOperation exception with text "This access control list is not in canonical form and therefore cannot be modified."

But, I'm trying to change it same way like I would work with e.g. FileSecurityDescriptor. May be I need to use different approach here?

Best regards
Kirill

Settings.Priority property not Granular Enough

How can we set the Priority property to a precise level (for example, 4).
Assigning 'Normal' to the Settings.Priority property is using '5' as the level. But what if we need to set it to 4?
Trying to change td.XmlText doesn't produce any effect.
td.Settings.XmlText comes back as unimplemented property.

TaskService call failed sometimes

Here is my code:
using (TaskService ts = TaskService.Instance)
{
using (var folder = ts.GetFolder(path))
{
}
}

However, the GetFolder throw an exception sometimes. I checked the the TaskService object when failed and fount it is not connected. Maybe I call the code two freqently?

How could I make sure it will always work?

The current version of the native library (1.3) does not support the original or minimum version of the ".NET Framework NGEN v4.0.30319" task (1.4/1.4)

When getting the definitions of certain tasks on mostly Windows 2012 servers, I get the following error:

The current version of the native library (1.3) does not support the original or minimum version of the ".NET Framework NGEN v4.0.30319" task (1.4/1.4)

I am running this code on a Windows 7 machine. (Perhaps it needs to be run on a machine with the native library v 1.4 - i.e. a recent server edition of Windows

Any ideas?
Thanks

Create process under user interactive terminal with higher permissions

If the answer is "not possible" I would completely understand, I'm asking just to be sure.

We have a lot of different end user systems which require regulare updates. Some of those updates require administrative permissions and some of these systems have a password requirement for those permissions.

Creating a task that runs under SYSTEM with the proper access rules added can run these updates.
But some of these updates might hang and require user interaction.
Is there a way to run them as system/administrator/administrators but with the UI part visible for the current user?

Using runas gives some flags that hint that it could, but so far my attempts have been fruitless.

Class already exists in mscorlib

In Visual Studio 2017 running under .NET 4.5, trying to move from TaskScheduler 2.5.20 to the latest or even the next build up throws the following error on build attempt:
CS0433 C# The type exists in both and 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'

The class it's referring to is IReadOnlyCollection. Looking at your source code, I see conditional statements; however, it looks like those are not functional.

Enforce 260 character limit for arguments <= Win 8

On windows 8 and below (including the server 2012 counterpart) tasks fail indefinitely (remain running till the machine is rebooted, but never actually execute) when the argument passed to them is longer than 260 characters with errorcode 2147942487.

Windows 10 doesn't seem to suffer from this problem (thankfully), could we add a filter/exception for this so other people don't bump their toes on this problem?

Change the "configure for" settings

Hi.
I have a simple question but I couldn't find the solution.
What's the code if I want to change the "configure for" settings?
e.g. Windows Vista -> Windows 10

Tasks not visible to library after upgrade to Windows 10 or Windows Server 2016

There are many tasks created on a Server machine using this library. Now the Server has been upgraded from Windows Server 2012 R2 to Windows Server 2016. All the tasks in the old server was exported and now imported in the new Server.

All the tasks are running correctly. But somehow when my application tries to find the tasks via FindTask(), it returns null. Below is the code I am using to find the task.

TaskService st = new TaskService();
Task oTask = st.FindTask("{A689610E-EC51-4288-A8EB-3847B4AB152D}");

Below is the snap of the Task scheduler with the same task working normal.
image

Steps to reproduce the issue:-

  1. Create a task with a unique name (say T1) using this API.
  2. Export the task T1 from the Task scheduler of windows machine manually.
  3. Delete the task T1 from the Task scheduler of windows machine manually.
  4. Import the task T1 from the Task scheduler of windows machine manually.
  5. Try to find the task T1 via st.FindTask("T1"); it returns null.

I am facing this issue on the Server and not able to read the tasks at all since I can't find them.
Please suggest a way to read all these tasks.

Thanks,
Jeet Doshi

.NET Core Port

We use your library, so thank you for making it available and maintaining it. We are looking at moving to .NET Core, and I'm wondering what your plans are for making a .NET Core version available as well.

I've attempted a port of the TaskService projects, and the only bit I found that wasn't supported is the WindowsImpersonationContext and the EventLog stuff.

Exception (23,8):UserId

I have had a few users get the following error but I have no idea what is causing it. Seems like it might be a user logon issue but I'm told they were using the correct Windows logon details. Does anyone know what the error means?

Exception: (23,8):UserId:
at
Microsoft.Win32.TaskScheduler.V2Interop.ITaskFolder.RegisterTaskDefinition(S
tring Path, ITaskDefinition pDefinition, Int32 flags, Object UserId, Object password, TaskLogonType LogonType, Object sddl)
at Microsoft.Win32.TaskScheduler.TaskFolder.RegisterTaskDefinition(String
path, TaskDefinition definition, TaskCreation createType, String userId, String password, TaskLogonType logonType, String sddl)
at Microsoft.Win32.TaskScheduler.TaskEditDialog.okBtn_Click(Object
sender, EventArgs e)

Please vote: Nullable Property Types

A question to the community: I'm considering making a breaking change to the library and introducing nullable TimeSpan and nullable DateTime properties to more accurately reflect how some properties are handled by the native library. For example, the native library would set the EndBoundary value of a trigger to "null" if it was not set. In this library (created before nullable types), that value is artificially recast as DateTime.MaxValue. Please provide your thoughts and votes. It would align this library more to the native library.

Access Denied

Hi!

I wrote a small class to try to schedule a task using TaskScheduler, but every username I try I get an "Access Denied" error.

I'm logged on a domain account which is administrator of this computer, and the provided XML was exported from a task I scheduled manually directly on Windows with the very same account, but I still get this:

System.UnauthorizedAccessException: 'Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))'

(I tried with simple examples like this one but got the same error)
Example:

using (TaskService ts = new TaskService())
{
  TaskDefinition td = ts.NewTask();
  td.RegistrationInfo.Description = "My first task scheduler";

  // Run Task whether user logged on or not
  td.Principal.LogonType = TaskLogonType.S4U;

  TimeTrigger trigger = new TimeTrigger();
  trigger.StartBoundary = DateTime.Now;
  trigger.Repetition.Interval = TimeSpan.FromMinutes(180);
  td.Triggers.Add(trigger);

  td.Actions.Add(new ExecAction(@"C:\simple.exe", null, null));

  ts.RootFolder.RegisterTaskDefinition("TaskName", td);
}

My JobScheduler Class:

public class JobScheduler
{
  public String Username { get { return Environment.UserDomainName + "\\" + Environment.UserName; } }
  public String Datetime { get { return DateTime.Now.ToString("yyyy-MM-dd") + "T" + DateTime.Now.ToString("hh:mm:ss.FFFFFFF"); } }
  public String DateJob { get { return DateTime.Now.AddDays(1).ToString("yyyy-MM-dd") + "T" + "15:00:00"; } }
  public String AppPath { get { return Application.ExecutablePath; } }
  public String UserId { get { return WindowsIdentity.GetCurrent().User.ToString(); } }

  public JobScheduler()
  {
  }

  public void Schedule()
  {
    TaskService ts = new TaskService();
    Boolean achou = false;
    foreach (Task t in ts.RootFolder.Tasks)
    {
      if (t.Name == Properties.Resources.JOBNAME)
      {
        achou = true;
      }
    }

    if (!achou)
    {
      String job = Properties.Resources.Job.ToString();
      job = job.Replace("$USERNAME", Username);
      job = job.Replace("$DATETIME", Datetime);
      job = job.Replace("$DATEJOB", DateJob);
      job = job.Replace("$USERID", UserId);
      //job = job.Replace("$USERID", "S-1-5-18");
      job = job.Replace("$APPPATH", AppPath);


      TaskDefinition td = ts.NewTask();
      td.XmlText = job;
      //ts.RootFolder.RegisterTaskDefinition(Properties.Resources.JOBNAME, td, TaskCreation.CreateOrUpdate, Environment.UserName, null, TaskLogonType.InteractiveToken, null);
      
      ts.RootFolder.RegisterTaskDefinition(Properties.Resources.JOBNAME, td);
    }
  }
}

My Base XML:

<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  <RegistrationInfo>
    <Date>2018-01-10T17:25:54.5633849</Date>
    <Author>FABER-CASTELL\CEVINICIUSZH</Author>
    <URI>\Horario</URI>
  </RegistrationInfo>
  <Triggers>
    <BootTrigger>
      <Enabled>true</Enabled>
    </BootTrigger>
    <LogonTrigger>
      <Enabled>true</Enabled>
    </LogonTrigger>
    <SessionStateChangeTrigger>
      <Enabled>true</Enabled>
      <StateChange>SessionUnlock</StateChange>
    </SessionStateChangeTrigger>
    <SessionStateChangeTrigger>
      <Enabled>true</Enabled>
      <StateChange>RemoteConnect</StateChange>
    </SessionStateChangeTrigger>
    <CalendarTrigger>
      <StartBoundary>2018-01-10T15:00:00</StartBoundary>
      <Enabled>true</Enabled>
      <ScheduleByDay>.
        <DaysInterval>1</DaysInterval>
      </ScheduleByDay>
    </CalendarTrigger>
  </Triggers>
  <Principals>
    <Principal id="Author">
      <UserId>S-1-5-21-1365381750-711603728-1050887974-14290</UserId>
      <LogonType>InteractiveToken</LogonType>
      <RunLevel>LeastPrivilege</RunLevel>
    </Principal>
  </Principals>
  <Settings>
    <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
    <DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
    <StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
    <AllowHardTerminate>true</AllowHardTerminate>
    <StartWhenAvailable>true</StartWhenAvailable>
    <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
    <IdleSettings>
      <StopOnIdleEnd>true</StopOnIdleEnd>
      <RestartOnIdle>false</RestartOnIdle>
    </IdleSettings>
    <AllowStartOnDemand>true</AllowStartOnDemand>
    <Enabled>true</Enabled>
    <Hidden>false</Hidden>
    <RunOnlyIfIdle>false</RunOnlyIfIdle>
    <WakeToRun>false</WakeToRun>
    <ExecutionTimeLimit>PT12H</ExecutionTimeLimit>
    <Priority>7</Priority>
  </Settings>
  <Actions Context="Author">
    <Exec>
      <Command>C:\Users\ceviniciuszh\AppData\Local\Apps\2.0\ZPWZ329E.WY5\JA5NP4R5.YHB\hora..tion_0000000000000000_0003.0000_b91bcafc9e60eb9a\Horario.exe</Command>
    </Exec>
  </Actions>
</Task>

Remove JetBrains dependency.

The latest version of the NuGet package has a dependency on JetBrains.Annotations (>= 11.0.0)

Can this be removed, it seems unnecessary.

Monthly Trigger for Last Day only

I'm trying to create a scheduled task to only run on the last day of the month. It doesn't seem like this is possible since the DaysOfMonth variable is required to be between 1 and 31. Is there anyway to have the scheduled task only run on the last day of the month?

[TaskEditor] What about UWP?

I'm trying to use the TaskEditor in one of my UWP projects.
Unfortunately I'm unable to do this, because the library depends on System.Windows.Forms.

Merge localized resources

Hi,
I tried to merge TaskScheduler together with german localized resources, like here: https://taskscheduler.codeplex.com/discussions/351311
Added these 3:
de\Microsoft.Win32.TaskScheduler.resources.dll
de\Microsoft.Win32.TaskSchedulerEditor.resources.dll
de\TimeSpan2.resources.dll

ILSpy shows .de. resources are there in merged library:
image

But dialog is not localized. Perhaps i missed something?
I start my project with
Dim ci As CultureInfo = New CultureInfo("de-DE")
Thread.CurrentThread.CurrentCulture = ci
Thread.CurrentThread.CurrentUICulture = ci

if I reference original libraries - localization is ok
Thanks

End/Disable Task?

Hi!
How can I end or enable/disable a specific task?
I know the way to remove(ts.RootFolder.DeleteTask("Taskname");) it but I just want to end or disable it.

native library (1.3) does not support the ".NET Framework NGEN v4.0.30319" task (1.4/1.4)

I've created a Console Application which queries 90 remote hosts to list their scheduled tasks. After listing the scheduled tasks of multiple hosts successfully, the wrapper throws the following error on multiple hosts:

The current version of the native library (1.3) does not support the original or minimum version of the ".NET Framework NGEN v4.0.30319" task (1.4/1.4)

Here's the stacktrace:

at Microsoft.Win32.TaskScheduler.Task.GetV2Definition(TaskService svc, IRegisteredTask iTask, Boolean throwError)
at Microsoft.Win32.TaskScheduler.Task.get_Definition()
at ScheduledTasks.ConsoleApp.Program.<>c.g__IsRelevant|2_0(Task x) in C:\path\to\ScheduledTasks.ConsoleApp\Program.cs:line 59

The "line 59" cited interrogates the Definition property of the Microsoft.Win32.TaskScheduler.Task object. Trying to access that Definition property seems to be what's throwing the error? I can provide the full code if that helps. In case it's relevant, the Console Application is running in Windows 7, and all of these queried hosts (those successful and those throwing errors) are running more modern operating systems.

What does this error mean? What can I change to be able to reliably use this Definition property?

can UI text and tab names be customized?

I would like to change the name of a tab (the "triggers" one, to "schedules" because it makes more sense in our project).

Can this be done or do the dialogs use the windows defaults exclusively with no customization possible?

Configure for combo blank on focus

Hi,
when i have XP Visual styles turned off and open TaskEditDialog "Configure for" combo appears to be blank on get focus, see below:
image

Trigger Type restriction

I want to restrict trigger type selection in editor (actually I want only calendar triggers and don't want event, logon etc triggers). Is that possible?

Best regards
Kirill

How to call function/method from TaskScheduler

Hi, I've been looking to contact you since long time.

I tested your product and working perfect but I have a concern.

I'm using VB.Net and want to call a VB method from "Microsoft.Win32.TaskScheduler".
I know that many examples describe about how to open file/application and so on which is external to vb.net ... but I want to call something internal (vb function/method)

How can i do that please? is it possible?

Please see below.

` "td.Actions.Add(New ExecAction("MyMethod()", "c:\test.log"))"

Sub MyMethod()

    MsgBox("Working !!!")

End Sub`

Unable to add a task - AccessDenied

In Windows any unprivileged user can create a task for yourself in Interactive Token mode ("run only when user is logged on").
Looks like I can't do that via TaskService. I've tried 2 ways:

	TaskService.Instance.AddTask("app_"+sid, QuickTriggerType.Logon, path, "-agent");

and

	using (var ts = new TaskService())
	{
		var td = ts.NewTask();
		td.Actions.Add(path, "-agent");
		var tr = td.Triggers.AddNew(TaskTriggerType.Logon);
		td.Principal.LogonType = TaskLogonType.InteractiveToken;
		ts.RootFolder.RegisterTaskDefinition("app_" + sid, td);
	}

TaskSchedulerEditor COM-Visible

Hi,
can you make TaskSchedulerEditor.dll COM-Visible? I am trying to use it from VBA, Microsoft.Win32.TaskScheduler.dll works fine, but not Microsoft.Win32.TaskSchedulerEditor.dll.

Thanks
Alex

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.