I have web application deployed on my local IIS 7, with application pool configured to work under built-in NETWORK SERVICE account. From this web application I need to check the status of my windows service (if it is started, stopped, etc). I’ve used such statements to get it:
public string GetServiceStatus(string machine, string service)
{
var service = new ServiceController(machine, service);
service.Refresh();
return service.Status;
}
The machine is an IP address of the host in my intranet (let it be 192.168.0.7), where the windows service is running – also under built-in NETWORK SERVICE account.
Unfortunately the code gives an exception:
service.Status threw an exception of type 'System.InvalidOperationException'
Cannot open MyService service on computer '192.168.0.7'. Access is denied.
Where is the problem ?
The problem is NETWORK SERVICE doesn’t have sufficient rights for controlling windows services. I needed to switch to another user context to be able to control it. But I didn’t want to do it for entire application. Instead I was searching for arbitrary piece of code execution under specific identity.
I’ve checked a lot of resources for impersonation included that shown by Malcolm Frexner. Because I’m working with Windows 7 (64bit) and also with Windows Server 2008 R2 (64bit), that I’ve found were not working for me. I ended up with such generic solution:
In addition I needed to create new user on my machine where the service is installed. User has to have permissions for controlling windows services – for that purpose it can be added to Administrators group.
Now I can start / stop my services and getting theirs current statuses in such way:
ImpersonateHappilyis just a function which takes parameters which are working with my operating system. Other similar solutions from the web useddwLogonTypeparameter passed to win 32 api functionLogonUserAwith values 2 or 9, while under my system value 8 is correct.BTW:
Impersonateis a wrapper function which sets up the impersonation and then passes it a lambda which does the actual work. The fancy computer science term for this style of writing code is higher-order programming.