IIS integration?

Topics: Errors
Feb 7, 2013 at 4:01 PM
Edited Jan 10, 2015 at 7:56 PM
Hello

I'm trying to integrate it in a web application but I get a com exception. Is it possible to use it in a web application in IIS?

I tried the example on the home page and the code throws an exception when it tries to register the task: ts.RootFolder.RegisterTaskDefinition(@"Test", td);

[COMException (0x80041318): (46,4):Task:]
Microsoft.Win32.TaskScheduler.V2Interop.ITaskFolder.RegisterTaskDefinition(String Path, ITaskDefinition pDefinition, Int32 flags, Object UserId, Object password, TaskLogonType LogonType, Object sddl) +0
Microsoft.Win32.TaskScheduler.TaskFolder.RegisterTaskDefinition(String Path, TaskDefinition definition, TaskCreation createType, String UserId, String password, TaskLogonType LogonType, String sddl) +154
Microsoft.Win32.TaskScheduler.TaskFolder.RegisterTaskDefinition(String Path, TaskDefinition definition) +314
WebApplication1._Default.AddTask(Object sender, EventArgs e) in C:\Users\XXXXXXXXXXX\Documents\Visual Studio 2010\Projects\WebApplication1\WebApplication1\Default.aspx.cs:39
System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(String eventArgument) +155
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3707
Coordinator
Feb 7, 2013 at 5:31 PM
Please search for discussions around IIS and ASP.NET and the permissions required to run in that environment.
Feb 8, 2013 at 7:25 AM
I have already searched the forum and I didn't find anything useful:
  1. Error Scheduling Task on 2008 R2: "The process must have appropriate permissions to connect to the TaskService"? Where in MSDN, i looked in MSDN but ...
  2. Schedule via ASP.NET: Didn't help.
  3. How to run task under the SYSTEM account without E_ACCESSDENIED: didn't help
  4. Can't create task on Windows Server 2008: didn't help
  5. who needs permissions?: "Localhost" didn't work
  6. Cannot instantiate the TaskService on a WCF service: not my case
  7. Unable to create tasks from ASP.NET under W2008: "moving from RegisterTaskDefinition to RegisterTask" didn't work
  8. Access denied when scheduling a task from windows phone application: not my case
  9. Unable to register task which will run even if user is not logged in: "Yes. You just need to specify the SYSTEM account when you register the task.", didn't work
  10. The task XML contains a value which is incorrectly formatted or out of range: not my case
  11. COMException (18,8) LogonType trying to create task with user id and password : not my case
  12. Can i access to the editor in asp.net?: Not what I looking for
  13. View Tasks: Object reference not set to an instance of an object: Not my problem
  14. Error on task creation, about LoginType: "TaskLogonType.ServiceAccount"and UserId = "System"", didn't work.
Did I miss something? Where I have to look? Can you post a link?
When this a frequent question is, why do you don't add it to the documentation?
Feb 8, 2013 at 8:22 AM
I have also tried to add IUSER to the Administrators but it didn't work.
Image
Coordinator
Feb 8, 2013 at 4:05 PM
Error 0x80041318 indicates that something in the definition violates either the permissions of what can be registered using the current credentials or violates something that can be registered under the target computer's version of the Task Scheduler. Please post the following to help me better troubleshoot your specific problem:

1) Just before calling RegisterTaskDefintion, have your program output the value of the Xml property for the TaskDefinition and post that here.
2) Tell me what user is being used to create the TaskService instance and what their permissions are on the target computer.
3) Tell me what user and TaskLogonType you are using when calling RegisterTaskDefinition and what their permissions are on the target computer.
Feb 11, 2013 at 6:37 AM
Edited Feb 11, 2013 at 6:53 AM
Thanks, I used the example on the Home in a asp.net page and I run it in IIS, the user is the "DefaultAppPool" and the domain is "IIS APPPOOL", the xml:
<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
  <RegistrationInfo>
    <Description>Does something</Description>
  </RegistrationInfo>
  <Triggers>
    <CalendarTrigger>
      <StartBoundary>2013-02-11T08:29:17.372</StartBoundary>
      <Enabled>true</Enabled>
      <ScheduleByDay>
        <DaysInterval>2</DaysInterval>
      </ScheduleByDay>
    </CalendarTrigger>
  </Triggers>
  <Settings>
    <MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
    <DisallowStartIfOnBatteries>true</DisallowStartIfOnBatteries>
    <StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
    <AllowHardTerminate>true</AllowHardTerminate>
    <StartWhenAvailable>false</StartWhenAvailable>
    <RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
    <IdleSettings>
      <Duration>PT10M</Duration>
      <WaitTimeout>PT1H</WaitTimeout>
      <StopOnIdleEnd>true</StopOnIdleEnd>
      <RestartOnIdle>false</RestartOnIdle>
    </IdleSettings>
    <AllowStartOnDemand>true</AllowStartOnDemand>
    <Enabled>true</Enabled>
    <Hidden>false</Hidden>
    <RunOnlyIfIdle>false</RunOnlyIfIdle>
    <WakeToRun>false</WakeToRun>
    <ExecutionTimeLimit>PT72H</ExecutionTimeLimit>
    <Priority>7</Priority>
  </Settings>
  <Actions>
    <Exec>
      <Command>notepad.exe</Command>
      <Arguments>c:\test.log</Arguments>
    </Exec>
  </Actions>
</Task>
I have tried to add all the permissions for the IUSER to the c:\windows\tasks folder and to add the IUSER to the administrators group but I get always the same error. I have tried also to use TaskLogonType.S4U and the TaskLogonType.ServiceAccount but the result was the same.

EDIT:
I have used the Marshal.ThrowExceptionForHR to check the error code and it turns out to be:
The task XML contains a value which is incorrectly formatted or out of range. (Exception from HRESULT: 0x80041318)
But if I run the same code not in IIS and therefore the user is my user it works. So I think is a permission problem but the exception has something with the xml to do???
Coordinator
Feb 11, 2013 at 3:51 PM
I completely agree that this is a permissions problem. In looking at the XML you posted I could not find a definitive problem. However, I have some ideas:
  • Try setting the Settings.Priority to a lower priority
  • Your ExecutionTimeLimit is longer than your trigger interval (3 days vs. 2 days)
If this solution is running on Windows 2008 or later, then setting permissions on the c:\windows\tasks folder is meaningless. You are looking at permissions of either how you are connecting to the TaskService instance (in the constructor) or the permissions of the user you are specifying in the RegisterTaskDefinition method. Let me know the details on those two items and I may be able to assist further.
Feb 11, 2013 at 11:31 PM
Thanks I have tried to reduce the priority and the execution time limits but I get the same exception.
For the moment is running in window 7 to test but after it should run on window 2008.
I use an empty constructor because I don't want to have users and passwords saved in some place, it should work with the the integrated user of IIS.
The registry task definition is also empty, I have taken the example from the home with the notepad and test.log file.
 // Get the service on the local machine
using (TaskService ts = new TaskService())
{
    // Create a new task definition and assign properties
    TaskDefinition td = ts.NewTask();
    td.RegistrationInfo.Description = "Does something";
    td.Settings.Priority = System.Diagnostics.ProcessPriorityClass.Normal;
    td.Settings.ExecutionTimeLimit = TimeSpan.FromMinutes(1);

    // 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
    try { ts.RootFolder.RegisterTaskDefinition(@"Test", td); }
    catch (COMException ex) { Marshal.ThrowExceptionForHR(ex.ErrorCode); }

    // Remove the task we just created
    //ts.RootFolder.DeleteTask("Test");
}
But I have made a little progress, if I change the identity of the DefaultAppPool to LocalService it works. Can I use the LocalService account to register the task without have to change the identity of the DefaultAppPool?
Coordinator
Feb 12, 2013 at 3:11 PM
Yes. In fact, I would recommend connecting to the TaskService using the LocalService account and then registering the task using the "LocalService" user, no password, and TaskLogonType.ServiceAccount. This is a permissions problem with the limited rights of the IUSER account.
Marked as answer by dahall on 4/3/2014 at 11:38 AM
Feb 12, 2013 at 4:02 PM
Edited Feb 12, 2013 at 4:02 PM
Ok so it is working, I post it there in case that somebody has the same problem
using (TaskService ts = new TaskService())
{
    // Create a new task definition and assign properties
    TaskDefinition td = ts.NewTask();
    td.RegistrationInfo.Description = "Does something";

    //Setting to run as Local Service whether the user is logged in or not
    td.Principal.LogonType = TaskLogonType.ServiceAccount;
    td.Principal.UserId = "LocalService";

    // 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
    try { ts.RootFolder.RegisterTaskDefinition(@"Test", td, TaskCreation.CreateOrUpdate, "LocalService", null, TaskLogonType.ServiceAccount); }
    catch (COMException ex) { Marshal.ThrowExceptionForHR(ex.ErrorCode); }

    // Remove the task we just created
    ts.RootFolder.DeleteTask(@"Test");
}
Marked as answer by dahall on 4/3/2014 at 11:38 AM
Feb 13, 2013 at 9:27 AM
Ah, now it works in IIS on Windows 7 but not on Windows Server 2008, it throws the following exception:

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

If I switch the application pool identity to Local Service it works again ... which is the difference between windows 7 and windows 2008?

.Net has a WindowsIdentity feature that can be used in a WindowsImpersonationContext but I can't get the local service login.
//this doesn't work, there isn't a local service login
using (var context = new WindowsIdentity(@"NT AUTHORITY\LOCAL SERVICE").Impersonate()) { }
Coordinator
Feb 13, 2013 at 4:23 PM
I would think you have an account privilege issue and that those privileges for the LocalService account are different across the two machines. You should check out the article at http://msdn.microsoft.com/en-us/library/windows/desktop/aa382140(v=VS.85).aspx and then confirm that LocalSystem and IUSER comply.
Marked as answer by dahall on 4/3/2014 at 11:38 AM