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

New Post: Delete IT After- Settings Tab - Immediately

$
0
0
Actually, the library's documentation says, "A TimeSpan value of 1 second indicates the task is set to delete when done. A value of TimeSpan.Zero indicates that the task should not be deleted."

Source code checked in, #98030

$
0
0
* Fixed bugs in CredentialsDialog that failed to pull in username or validate password * Fixed ommision in task editors where alternate owners did not force a password retrieval

New Post: Delete IT After- Settings Tab - Immediately

$
0
0
Thanks for the reply. I tried giving TimeSpan value of 1 second but the Task Created in system's task scheduler shows '1 second' instead of 'Immediately' .

New Post: About the TriggerString

$
0
0
I read the source code and found that is a API: GetTriggerString for V1, but not V2.
So Task Scheduler Managed Wrapper implement it.
But I found the output string of V2 is same with the windows "task scheduler".
So it is possible that is some API of V2 to getTriggerString, no need to implement it.

New Post: About the TriggerString

$
0
0
The native V2 library does not include the trigger string output. It is implemented inside the "Task Scheduler" tool. I implemented it as part of the wrapper.

New Post: Delete IT After- Settings Tab - Immediately

$
0
0
I see the problem now. When I originally wrote the library, there were not nullable types supported in either C# or VB.NET. The native library uses strings that can have the following values:
  • 'null' == 'Never delete'
  • 'PT0S' (or TimeSpan.Zero) == 'Immediately'
  • 'PTxx' == other times
I needed a solution that would work without nullable types, so I chose to implement the library using Microsoft's solution for the V1 library, which is:
  • TimeSpan.Zero == 'Never delete'
  • TimeSpan.FromSeconds(1) == 'Immediately'
  • TimeSpan (other) == other times
I believe this is the discrepancy you're seeing. Sorry for the confusion.

Updated Wiki: Home

$
0
0
This project provides a wrapper for the Windows Task Scheduler. It aggregates the multiple versions, provides an editor and allows for localization.

NuGet
This project's assemblies are available via NuGet. 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 and 4.0.
  • Unlike the base library, this wrapper helps to create and view tasks up and down stream.
  • Written in C#, but works with any .NET language including scripting languages.
  • Supports almost all V2 native properties, even under V1 systems.
  • Maintain EmailAction and ShowMessageAction under Win8 where they have been deprecated using PowerShell
  • 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 "custom" triggers under Win8 and later.
  • Numerous work-arounds and checks to compensate for base library shortcomings.
The project supports a number of languages and, upon request, is ready to support others. The currently supported languages include:
  • English
  • Spanish
  • Italian
  • French
  • Chinese (Simplified)
  • German
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
There is a second library that 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:
  • 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.
  • Simplified classes for pulling events from the system event log.
  • Action editor dialog
  • Trigger editor dialog
  • Task editor dialog and tabbed control
  • Event viewer dialog
  • Task / task folder selection dialog
  • Task history viewer
  • Task run-times viewer
  • Task creation wizard
  • Task service connection dialog
COM Handler Project Template
If you are writing your own custom Task Scheduler COM Handler based on the ITaskHandler interface, there is a project template available that will stub out the majority of the work to create it in C# and a sample to show a complete one. If running your own code, this model provides much better interaction, control and memory management than running an executable.

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
{
   staticvoid Main(string[] args)
   {
      // Get the service on the local machineusing (TaskService ts = new TaskService())
      {
         // Create a new task definition and assign properties
         TaskDefinition td = ts.NewTask();
         td.RegistrationInfo.Description = "Does something";

         // 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
         ts.RootFolder.RegisterTaskDefinition(@"Test", td);

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

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 MSDN around it that may further help you understand how to use this library.

Updated Wiki: Examples

$
0
0

Examples Home Page

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

   Console.WriteLine("\n***Checking task creation***");
   try
   {
      // Create a new task definition and assign properties
      TaskDefinition td = ts.NewTask();
      td.Data = "Your data";
      td.Principal.UserId = user;
      td.Principal.LogonType = TaskLogonType.InteractiveToken;
      td.RegistrationInfo.Author = "dahall";
      td.RegistrationInfo.Description = "Does something";
      td.RegistrationInfo.Documentation = "Don't pretend this is real.";
      td.Settings.DisallowStartIfOnBatteries = true;
      td.Settings.Enabled = false;
      td.Settings.ExecutionTimeLimit = TimeSpan.FromHours(2);
      td.Settings.Hidden = false;
      td.Settings.IdleSettings.IdleDuration = TimeSpan.FromMinutes(20);
      td.Settings.IdleSettings.RestartOnIdle = false;
      td.Settings.IdleSettings.StopOnIdleEnd = false;
      td.Settings.IdleSettings.WaitTimeout = TimeSpan.FromMinutes(10);
      td.Settings.Priority = System.Diagnostics.ProcessPriorityClass.Normal;
      td.Settings.RunOnlyIfIdle = false;
      td.Settings.RunOnlyIfNetworkAvailable = false;
      td.Settings.StopIfGoingOnBatteries = true;
      if (newVer)
      {
         td.Principal.RunLevel = TaskRunLevel.Highest; //.LUA;
         td.RegistrationInfo.Source = "Test App";
         td.RegistrationInfo.URI = new Uri("test://app");
         td.RegistrationInfo.Version = new Version(0, 9);
         td.Settings.AllowDemandStart = true;
         td.Settings.AllowHardTerminate = true;
         td.Settings.Compatibility = TaskCompatibility.V2;
         td.Settings.DeleteExpiredTaskAfter = TimeSpan.FromMinutes(1);
         td.Settings.MultipleInstances = TaskInstancesPolicy.StopExisting;
         td.Settings.StartWhenAvailable = true;
         td.Settings.WakeToRun = false;
         td.Settings.RestartCount = 5;
         td.Settings.RestartInterval = TimeSpan.FromSeconds(100);
      }

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

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

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

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

         if (preWin7)
         {
            // Create triggers that fire after various system states are changed
            td.Triggers.Add(new SessionStateChangeTrigger { StateChange =
               TaskSessionStateChangeType.ConsoleConnect, UserId = user });
            td.Triggers.Add(new SessionStateChangeTrigger { StateChange =
               TaskSessionStateChangeType.ConsoleDisconnect });
            td.Triggers.Add(new SessionStateChangeTrigger { StateChange =
               TaskSessionStateChangeType.RemoteConnect });
            td.Triggers.Add(new SessionStateChangeTrigger { StateChange =
               TaskSessionStateChangeType.RemoteDisconnect });
            td.Triggers.Add(new SessionStateChangeTrigger { StateChange =
               TaskSessionStateChangeType.SessionLock, UserId = user });
            td.Triggers.Add(new SessionStateChangeTrigger { StateChange =
               TaskSessionStateChangeType.SessionUnlock });
         }
      }

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

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

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

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

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

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

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

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

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

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

XML example
Tasks can be saved or created from scratch in XML and then registered directly as an alternative to setting individual properties.
// Save a Task's XML to a filestring xml = TaskService.Instance.GetTask("\\Temp").Xml;
System.IO.File.WriteAllText("localfile.xml", td.XmlText, System.Text.Encoding.Unicode);
// Create a Task using XML with user information
TaskService.Instance.RootFolder.RegisterTask("NewTask1", xml, TaskCreation.Create,
   "SYSTEM", null, TaskLogonType.SystemAccount);
// Create a Task directly from a file
TaskService.Instance.RootFolder.ImportTask("NewTask2", "localfile.xml");
// Load an XML file for editing, change a property, and register
TaskDefintion td  = TaskService.Instance.NewTask();
td.XmlText = System.IO.File.ReadAllText("localfile.xml");
td.Settings.AllowDemandStart = true;
TaskService.Instance.RootFolder.RegisterTaskDefinition("NewTask3", td);

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

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

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

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

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

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

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

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

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

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

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

New Post: Wrapper is providing type 'NotifyCollectionChangedEventArgs'

$
0
0
Okay, thank you for your advice.

Closed Unassigned: TaskDefinition.Actions always empty in v1 since release 2.5.0 [12328]

$
0
0
It's all in the title :)
Actions are always empty in v1 mode (XP/2003) since the version 2.5.0. The last working version is 2.4.2.

Closed Issue: The task has been configured with an unsupported combination of account settings and run time options. [12293]

$
0
0
Hi,

Since I've updated to the latest stable release(2.5.4) I'm getting the following error:
_The task has been configured with an unsupported combination of account settings and run time options. (Exception from HRESULT: 0x80041314)_
This did not happen with version 2.4.2 and lower (doublechecked it)

What happens is:
I'm contacting a Win7 machine but i specify the taskservice to use 1.1 version.
Then i register a task with the serviceaccount.
I've been able to reproduce this error several times

Can you confirm this as a bug?

Code (C#):
```
using (TaskService ts = new TaskService(hostname, null, null, null, true))
{
TaskDefinition tduser = ts.NewTask();
bool newVer = (ts.HighestSupportedVersion >= new Version(1, 2));
tduser.Actions.Add(new ExecAction("cmd", "Do something", null));
tduser.Settings.DisallowStartIfOnBatteries = false;
tduser.Settings.StopIfGoingOnBatteries = false;
tduser.RegistrationInfo.Description = "My Task";
if (newVer) //v2.0
{
tduser.Principal.RunLevel = TaskRunLevel.Highest;
tduser.Settings.AllowDemandStart = true;
}
ts.RootFolder.RegisterTaskDefinition("My Task", tduser, TaskCreation.CreateOrUpdate,
"system", null, TaskLogonType.ServiceAccount); //this crashed
ts.GetTask("My Task").Run();
}
```

Source code checked in, #98031

$
0
0
* Functional wizard version of configuration troubleshooter

Source code checked in, #98032

$
0
0
* Mimic fixes into TaskOptionsEditor

Created Unassigned: The system cannot find the path specified. [12350]

$
0
0
Hi,

After some changes library cannot get data from remote server.
Details: I use win7 and try to get state of task on win2003. TaskService is used with forceV1=true.
Code to reproduce:
```
using (TaskService ts = new TaskService(targetServer2003, user, domain, pwd, true ))
{
List<TaskState> taskList = new List<TaskState>();
foreach (Task task in ts.RootFolder.Tasks)
taskList.Add(task.State);// error occurs here
}
```
Error:
```
The system cannot find the path specified. (Exception from HRESULT: 0x80070003)

at Microsoft.Win32.TaskScheduler.V1Interop.ITaskScheduler.Activate(String Name, Guid& riid)
at Microsoft.Win32.TaskScheduler.TaskService.GetTask(ITaskScheduler iSvc, String name)
at Microsoft.Win32.TaskScheduler.Task.V1Reactivate()
at Microsoft.Win32.TaskScheduler.Task.get_State()
at TestRemoteConnectionTo2003.Program.Main(String[] args) in c:\users\akolpako\documents\visual studio 2015\Projects\TestRemoteConnectionTo2003\TestRemoteConnectionTo2003\Program.cs:line 18
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
```
The bug had appeared after changes in TaskService.cs. After adding the next line:
name = name.TrimStart('\\');
```
internal static V1Interop.ITask GetTask(V1Interop.ITaskScheduler iSvc, string name)
{
name = name.TrimStart('\\');
if (string.IsNullOrEmpty(name))
throw new ArgumentNullException(nameof(name));
try
{
return iSvc.Activate(name, ref ITaskGuid);
}
catch (System.UnauthorizedAccessException)
{
// TODO: Take ownership of the file and try again
throw;
}
catch (System.ArgumentException)
{
return iSvc.Activate(name + ".job", ref ITaskGuid);
}
catch { throw; }
}
```
Some time method is called with path argument instead of name. (For example when you are reading a status). It can lead to an error.
Path that leads to the error:
![Image](http://i68.tinypic.com/15i50mx.png)

Commented Unassigned: The system cannot find the path specified. [12350]

$
0
0
Hi,

After some changes library cannot get data from remote server.
Details: I use win7 and try to get state of task on win2003. TaskService is used with forceV1=true.
Code to reproduce:
```
using (TaskService ts = new TaskService(targetServer2003, user, domain, pwd, true ))
{
List<TaskState> taskList = new List<TaskState>();
foreach (Task task in ts.RootFolder.Tasks)
taskList.Add(task.State);// error occurs here
}
```
Error:
```
The system cannot find the path specified. (Exception from HRESULT: 0x80070003)

at Microsoft.Win32.TaskScheduler.V1Interop.ITaskScheduler.Activate(String Name, Guid& riid)
at Microsoft.Win32.TaskScheduler.TaskService.GetTask(ITaskScheduler iSvc, String name)
at Microsoft.Win32.TaskScheduler.Task.V1Reactivate()
at Microsoft.Win32.TaskScheduler.Task.get_State()
at TestRemoteConnectionTo2003.Program.Main(String[] args) in c:\users\akolpako\documents\visual studio 2015\Projects\TestRemoteConnectionTo2003\TestRemoteConnectionTo2003\Program.cs:line 18
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
```
The bug had appeared after changes in TaskService.cs. After adding the next line:
name = name.TrimStart('\\');
```
internal static V1Interop.ITask GetTask(V1Interop.ITaskScheduler iSvc, string name)
{
name = name.TrimStart('\\');
if (string.IsNullOrEmpty(name))
throw new ArgumentNullException(nameof(name));
try
{
return iSvc.Activate(name, ref ITaskGuid);
}
catch (System.UnauthorizedAccessException)
{
// TODO: Take ownership of the file and try again
throw;
}
catch (System.ArgumentException)
{
return iSvc.Activate(name + ".job", ref ITaskGuid);
}
catch { throw; }
}
```
Some time method is called with path argument instead of name. (For example when you are reading a status). It can lead to an error.
Path that leads to the error:
![Image](http://i68.tinypic.com/15i50mx.png)
Comments: ** Comment from web user: kolpakov_a **

For status reading that can be fixed in Task.cs if we use Name instead of path:
```
internal void V1Reactivate()
{
V1Interop.ITask iTask = TaskService.GetTask(TaskService.v1TaskScheduler, Name);
if (iTask != null)
v1Task = iTask;
}
```


New Post: A password must be supplied

$
0
0
Hi,

New build works fine when you add a new task but does not work with an old task when you try to edit it.
For this case UserId always is not empty and check at Task.cs does not work:
        public bool RequiresPassword() => LogonType == TaskLogonType.InteractiveTokenOrPassword ||
            LogonType == TaskLogonType.Password || (LogonType == TaskLogonType.S4U && UserId != null);

New Post: A password must be supplied

$
0
0
Thank you for doing better testing than me. I have corrected and it will be in the next release.

Commented Unassigned: The system cannot find the path specified. [12350]

$
0
0
Hi,

After some changes library cannot get data from remote server.
Details: I use win7 and try to get state of task on win2003. TaskService is used with forceV1=true.
Code to reproduce:
```
using (TaskService ts = new TaskService(targetServer2003, user, domain, pwd, true ))
{
List<TaskState> taskList = new List<TaskState>();
foreach (Task task in ts.RootFolder.Tasks)
taskList.Add(task.State);// error occurs here
}
```
Error:
```
The system cannot find the path specified. (Exception from HRESULT: 0x80070003)

at Microsoft.Win32.TaskScheduler.V1Interop.ITaskScheduler.Activate(String Name, Guid& riid)
at Microsoft.Win32.TaskScheduler.TaskService.GetTask(ITaskScheduler iSvc, String name)
at Microsoft.Win32.TaskScheduler.Task.V1Reactivate()
at Microsoft.Win32.TaskScheduler.Task.get_State()
at TestRemoteConnectionTo2003.Program.Main(String[] args) in c:\users\akolpako\documents\visual studio 2015\Projects\TestRemoteConnectionTo2003\TestRemoteConnectionTo2003\Program.cs:line 18
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
```
The bug had appeared after changes in TaskService.cs. After adding the next line:
name = name.TrimStart('\\');
```
internal static V1Interop.ITask GetTask(V1Interop.ITaskScheduler iSvc, string name)
{
name = name.TrimStart('\\');
if (string.IsNullOrEmpty(name))
throw new ArgumentNullException(nameof(name));
try
{
return iSvc.Activate(name, ref ITaskGuid);
}
catch (System.UnauthorizedAccessException)
{
// TODO: Take ownership of the file and try again
throw;
}
catch (System.ArgumentException)
{
return iSvc.Activate(name + ".job", ref ITaskGuid);
}
catch { throw; }
}
```
Some time method is called with path argument instead of name. (For example when you are reading a status). It can lead to an error.
Path that leads to the error:
![Image](http://i68.tinypic.com/15i50mx.png)
Comments: ** Comment from web user: dahall **

Thank you. This will be fixed in 2.5.15.

Source code checked in, #98033

$
0
0
* Fixed problem with creating V1 non-calendar triggers * Fixed problem getting V1 task from UNC

New Post: A password must be supplied

$
0
0
I have tested again and found a new issue) Sometime unnecessary dialog appears for current user. I don't know how but right now I have two tasks with current user as runner but its name has different cases.
I guess string.Compare(UserId, System.Security.Principal.WindowsIdentity.GetCurrent().Name) should compare with ignore case (StringComparison.OrdinalIgnoreCase).

Thank you.
Viewing all 2206 articles
Browse latest View live




Latest Images