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

New Post: Quartz.Net

$
0
0
Thanks for the idea. I'll collaborate with the authors of Quartz.Net to see what could be done.

New Post: getting security information for a task

$
0
0
I think you are looking for one of two things: 1) The user account under which the task was created - in which case use Task.Definition.RegistrationInfo.Author or 2) The user account under which the task runs - in which case use Task.Definition.Principal.ToString() (which will pull either UserId or GroupId property based on logon type).

New Post: getting security information for a task

$
0
0
Thanks, I spent a better part of the day looking in the tasksecurity class. LOL. I went and looked at your source code for the interface and was able to identify the task.definition class.
Just getting familiar with the wrapper.

I would like to extend a big thanks for this work.
Now on to figuring out how to change the password for the Task.

I know peeps like to see code, that is how we learn. Simple stuff so far, but just in case someone else runs into this.
   class Program
    {
        static void Main()
        {

            using (TaskService ts = new TaskService("wtxwt0017"))
            {
                EnumTaskFolders(ts.RootFolder);

            }



        }

        public static void EnumTaskFolders(TaskFolder taskFolder)
        {
            foreach (Task task in taskFolder.Tasks)
            {
                listTasks(task);

            }
            Console.ReadLine();
        }

        public static void listTasks(Task t)
        {
            
            string userid = t.Definition.Principal.ToString();       

            Console.WriteLine(string.Format("task name = {0} , userid - {1}", t.Name, userid));
        }

       
    }
    
}

New Post: getting security information for a task

$
0
0
The only way to change the password for a task is to re-register the task.

Source code checked in, #94124

New Post: Get Delay from Trigger?

$
0
0
How do I get the delay time from a trigger?

For instance...
Dim delayTime as short
Using taskServiceObject As TaskService = New TaskService()
  Dim taskObject As Microsoft.Win32.TaskScheduler.Task = taskServiceObject.GetTask("mytask")

  If (taskObject Is Nothing) = False Then ' Makes sure that the task exists and we don't get a Null Reference Exception.
    With taskObject.Definition.Triggers.Item(0)
      If .TriggerType = TaskTriggerType.Logon Then
        // Get Delay Time Here and store it in a variable
        delayTime = .Delay????
      End If
    End With
  End If
End Using
Anybody have a clue how to get that?

New Post: Get Delay from Trigger?

$
0
0
First of all, tasks do not have to have any triggers so unless you know there is at least one trigger, you should check Triggers.Count > 0 before getting the indexed trigger.

To answer your question, I believe you are looking for the following:
Dim delayTime As TimeSpan
Using taskServiceObject As TaskService = New TaskService()
   Dim taskObject As Microsoft.Win32.TaskScheduler.Task = taskServiceObject.GetTask("mytask")
   ' Makes sure that the task exists and we don't get a Null Reference Exception.
   If (taskObject IsNot Nothing) And (taskObject.Definition.Triggers.Count > 0) Then
      Dim trigger As Trigger = taskObject.Definition.Triggers.Item(0)
      If (trigger.TriggerType = TaskTriggerType.Logon) And (TypeOf trigger Is ITriggerDelay) Then
         ' Get Delay Time Here and store it in a variable
         delayTime = CType(trigger, ITriggerDelay).Delay
      End If
   End If
End Using
Technically, you don't need to check if the trigger type is Logon unless your code requires it. If you need seconds or milliseconds from the TimeSpan object, there are methods and properties on that object to extract that details.

Closed Unassigned: System.IO.FileNotFoundException V1Interop.ITaskScheduler.Activate [11938]

$
0
0
Can you help me, I just got this error on Windows XP Pro (SP3)

System.IO.FileNotFoundException: The system cannot find the file specified. (Exception from HRESULT: 0x80070002)
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.TaskService.GetTask(String taskPath)
at SmartShare.schedulemanager.ScheduleSleep(Int32 idleSetting)
at SmartShare.My.MyApplication.MyApplication_Startup(Object sender, StartupEventArgs e)
Comments: Unknown resolution

Closed Unassigned: Problem to edit task with editor [11937]

$
0
0
Hi, i have a problem with generating the code after execution

My code :

```
TaskService mgr = new TaskService();
TaskEditDialog dlg = new TaskEditDialog(mgr.RootFolder.Tasks[0], false, false);
```


Une exception non gérée du type 'System.ArgumentOutOfRangeException' s'est produite dans Microsoft.Win32.TaskSchedulerEditor.dll

Informations supplémentaires : L'argument spécifié n'était pas dans les limites de la plage des valeurs valides.

Thx

Jerem
Comments: Unknown resolution

Closed Unassigned: Remote windows server 2003 Task scheduling access [11880]

$
0
0
hi,

when i tried to connect a remote server(windows 2003) using the line,

Microsoft.Win32.TaskScheduler.TaskService _taskservice = new Microsoft.Win32.TaskScheduler.TaskService(servername, username, domain, Password);

it is throwing multiple errors like "The request is not supported. (Exception from HRESULT: 0x80070032)" and sometimes with the code 0x80070006

is it possible to connect to windows server 2003 through Microsoft.win32.taskscheduler? because 2003 server doesnt have GUI for Task Scheduler.

can anyone please help me on this..
Comments: Unknown resolution

Closed Unassigned: System.NullReferenceException exception in web service call task [11850]

$
0
0
I wrote an c# console app which calls web service.
I needed to run this app for every night, so I decided to use this task scheduler as it seems a good one to do my job.

But I got an issue which says "Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object. ..."
I read many articles described about same issue, but nothing is helpful.

For example,

```
TaskDefinition td = ts.NewTask();
td.RegistrationInfo.Description = "Does something";
td.Principal.Id = "any string";
td.Principal.GroupId = "NETWORK SERVICE";
td.Principal.RunLevel = TaskRunLevel.LUA;
td.Principal.LogonType = TaskLogonType.S4U;
ts.RootFolder.RegisterTaskDefinition(@"NetsuiteInvoiceGetTask", td);
```

My OS is Windows7 64bit.
Can anyone help me? Thanks.
Comments: Unknown resolution

Updated Wiki: Documentation

$
0
0

Documentation Home Page

There is a help file included with the download that provides an overview of the various classes. The Microsoft MSDN documentation provides an excellent overview of the Task Scheduler along with details around security and permission, idle conditions, and trigger repetition.
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";

         // Add a trigger that, starting tomorrow, will fire every other week on Monday// and Saturday and repeat every 10 minutes for the following 11 hours
         WeeklyTrigger wt = new WeeklyTrigger();
         wt.StartBoundary = DateTime.Today.AddDays(1);
         wt.DaysOfWeek = DaysOfTheWeek.Monday | DaysOfTheWeek.Saturday;
         wt.WeeksInterval = 2;
         wt.Repetition.Duration = TimeSpan.FromHours(11);
         wt.Repetition.Interval = TimeSpan.FromMinutes(10);
         td.Triggers.Add(wt)

         // 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);
      }
   }
}

Here's the same as above but in VB.NET

Imports Microsoft.Win32.TaskScheduler

Module Module1

    Sub Main()
        Using ts AsNew TaskService()
            ' Create a new task definition and assign propertiesDim td As TaskDefinition = ts.NewTask
            td.RegistrationInfo.Description = "Does something"' Add a trigger that will, starting tomorrow, fire every other week on Monday' and Saturday and repeat every 10 minutes for the following 11 hoursDim wt AsNew WeeklyTrigger()
            wt.StartBoundary = DateTime.Today.AddDays(1)
            wt.DaysOfWeek = DaysOfTheWeek.Monday Or DaysOfTheWeek.Saturday
            wt.WeeksInterval = 2
            wt.Repetition.Duration = TimeSpan.FromHours(11)
            wt.Repetition.Interval = TimeSpan.FromMinutes(10)
            td.Triggers.Add(wt)

            ' Add an action (shorthand) that runs Notepad
            td.Actions.Add(New ExecAction("notepad.exe", "c:\test.log"))

            ' Register the task in the root folder
            ts.RootFolder.RegisterTaskDefinition("Test", td)
        EndUsingEndSubEndModule

If you're really into shorthand code, here's almost the same functionality as the C# code above, but much shorter:

using System;
using Microsoft.Win32.TaskScheduler;

class Program
{
   staticvoid Main(string[] args)
   {
      new TaskService().AddTask("Test", new DailyTrigger { DaysInterval = 2 },
         new ExecAction("notepad.exe", "c:\\test.log", null));
   }
}

Alternately, you can use the library declaratively or "fluently":

Task t = new TaskServer().Execute("notepad.exe").WithArguments(@"c:\test.log").Every(2).Days().AsTask("Test");

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 { DaysInterval = 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.SecurityDescriptorSddlForm = "O:COG:CGD::(A;;RPWPCCDCLCSWRCWDWOGA;;;S-1-0-0)";
         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 a.m. 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");
}

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: UserAccountDomain and UserName NULL when ConnectedDomain and ConnectedUser have values

$
0
0
Hi,

I have started using this managed wrapper but came into this weird problem. When I have tried to Register the Task using the UserAccountDomain and UserName properties from the Task Service which is previously instantiated with a Machine, Domain, UserName and Password, I saw that both properties are holding null value.

Whereas, the deprecated properties ConnectedDomain and ConnectedUser are showing the values properly. Any idea?

I'm using version 2.3.0.22156 where the run time version in v4.0.30319.

Thanks,

UBK

New Post: UserAccountDomain and UserName NULL when ConnectedDomain and ConnectedUser have values

$
0
0
This is by design and relates to serialization. The UserAccountDomain and UserName properties will return null if they match the current user that is executing the library.

New Post: UserAccountDomain and UserName NULL when ConnectedDomain and ConnectedUser have values

$
0
0
Hi dahall,

Thanks for your quick response.

So, I have tried with a different account. i.e. I have connected with my credentials and creating the task using a different credential. In that case, I have seen that the ConnectedDomain and ConnectedUser are showing the values for the other credential that I am using. UserName property is also showing up and it is same as ConnectedUser but UserDomain is still NULL. What I need to do to have it populated?

For now I am using ConnectedDomain and ConnectedUser properties but I am looking for a better option since those properties are marked as deprecated.

Thanks,

UBK

New Post: UserAccountDomain and UserName NULL when ConnectedDomain and ConnectedUser have values

$
0
0
When UserDomain is NULL, does ConnectedDomain match the domain specified by System.Environment.UserDomain? I may have a logic error if you are getting UserName but not UserDomain.

Created Unassigned: Recently we got AccessViolationException [12019]

$
0
0
Hi! Recently we've got the following exception. It happened one time and we cannot reproduce it.

System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
at Microsoft.Win32.TaskScheduler.V2Interop.IRegisteredTask.get_Definition()
at Microsoft.Win32.TaskScheduler.Task.GetV2Definition(TaskService svc, IRegisteredTask iTask, Boolean throwError)
at Microsoft.Win32.TaskScheduler.Task.get_Definition()


We run our WPF application on Win7, .Net 3.5.

Commented Unassigned: Recently we got AccessViolationException [12019]

$
0
0
Hi! Recently we've got the following exception. It happened one time and we cannot reproduce it.

System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
at Microsoft.Win32.TaskScheduler.V2Interop.IRegisteredTask.get_Definition()
at Microsoft.Win32.TaskScheduler.Task.GetV2Definition(TaskService svc, IRegisteredTask iTask, Boolean throwError)
at Microsoft.Win32.TaskScheduler.Task.get_Definition()


We run our WPF application on Win7, .Net 3.5.
Comments: ** Comment from web user: dahall **

I've just gone through the code and cannot find a place where there is even a memory allocation or deallocation related to that code. The particular line is even within a "try" clause. My only guess (and sorry to push this off but I really can't see anything that would lead to that exception) is that it has something to do with Microsoft's internal library. That particular method call (IRegisteredTask.get_Definition) is a call into one of Microsoft's COM objects. It would not be surprising given the complexity of that result (ITaskDefinition) and I could see a corner case in creating the return object. I'll leave this issue open for a few months in case you are able to narrow the problem down though.

Source code checked in, #94299

$
0
0
* Added static Instance property to TaskService * Simplified some interop helper methods
Viewing all 2206 articles
Browse latest View live


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