Impersonation exception invoking DirectoryEntry.Invoke method

0

I have a frustrating problem trying to use the System.DirectoryServices.DirectoryEntry.Invoke() method to recycle app pools on a remote IIS server.

The basic context is two client machines and an IIS 7.0 server machine (Windows 2008 Server), myServer, all in the same Windows domain. I want to run code on the client machines to recycle an AppPool on the IIS server.

Here's the relevant code snippet:

DirectoryEntry directoryEntry = new DirectoryEntry("IIS://myServer/W3SVC/AppPools/SomeAppPool", domainUserid, password, AuthenticationTypes.Secure);

directoryEntry.Invoke("Recycle", null);

From one client machine, the code runs successfully, but on the other client machine, the code throws an exception relating to impersonation (see below). I'm logged in as the same domain user on both client machines, and use the same domain user information in the code.

I've checked the server-side Event Viewer and other logs to see if there's some obvious difference in how the request is processed on the server, and done a significant amount of googling without success.

Can anyone give a clue as to what to look for or what diagnostics I can run (on either the client machines or on the server machine) to determine why this is happening?

Thanks for any help! Martin

2011-08-10 22:35:39,478 [10] WARN - ActionRestartIIS: Exception restarting IIS System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Runtime.InteropServices.COMException (0x80070542): Either a required impersonation level was not provided, or the provided impersonation level is invalid. (Exception from HRESULT: 0x80070542) --- End of inner exception stack trace --- at System.DirectoryServices.DirectoryEntry.Invoke(String methodName, Object[] args)

iis
impersonation
asked on Stack Overflow Aug 11, 2011 by user304582

1 Answer

0

In that fine tradition of answering one's own questions, here's what I learnt. I modified my code to use System.Management classes and these seem to work better across domains. Sample code below:

ConnectionOptions connectionOptions = new ConnectionOptions();

connectionOptions.Authority = "ntlmdomain:" + this.domain;

connectionOptions.Username = this.username; connectionOptions.Password = this.password;

connectionOptions.EnablePrivileges = true;

connectionOptions.Authentication = AuthenticationLevel.PacketPrivacy;

ManagementScope managementScope = new ManagementScope(@"\" + this.iisserver + @"\root\microsoftiisv2", connectionOptions);

managementScope.Connect();

ManagementObject appPool = new ManagementObject(managementScope, new ManagementPath("IISApplicationPool.Name='W3SVC/AppPools/" + apppool + "'"), null);

appPool.InvokeMethod("Recycle", null, null);

answered on Stack Overflow Aug 12, 2011 by user304582

User contributions licensed under CC BY-SA 3.0