views:

1683

answers:

4

Hi,

I need to change Logon user for a Windows service programmatically. And I am using the following code to do that:

string objPath = string.Format("Win32_Service.Name='{0}'", ServiceName);
using (ManagementObject service = new ManagementObject(new ManagementPath(objPath)))
{
object[] wmiParams = new object[11];

if (PredefinedAccount)
    {
        wmiParams[6] = "LocalSystem";
            wmiParams[7] = "";
    }
    else
    {
        wmiParams[6] = ServiceUsername; // provided by user
            wmiParams[7] = ServicePassword; // provided by user
    }

    object invokeResult = service.InvokeMethod("Change", wmiParams);

// handle invokeResult - no error up to this point
}

This code works in 90% of situations, but in some situations service cannot be started due to logon failure. There is usually no error on InvokeMetod but when we try to start the service we get the following error: System.InvalidOperationException: Cannot start service X on computer '.'. --> System.ComponentModel.Win32Exception: The service did not start due to a logon failure.

The workaround solution is simple, we just need to enter the same credentials via Windows interface and problem is solved.

So my question is, has anybody experienced the similar problem with ManagementObject because it seems that in some situation it does not relate Username and password to windows service?

A: 

Do you notice any patterns amongst those failures? Same machine? Same OS? Same user? Does the user have "logon as service" or "logon interactively" rights? Personally, I am not familiar with this method of specifying the user for a service. I would have thought you would have to restart the service, but I guess not if it works 90% of the time.

flipdoubt
Well it depends, on various OS-s. There is no pattern. Sometimes this occurs if password is short (less then 7 characters). In all these cases problem was solved when user entered the same username and password via Windows default interface. So we presume it is something in our code or the ManagementObject we are using.
Anne
+2  A: 

I'm not sure whether this problem is solved. But we just encountered the similar problem and we figured out that it's because the account has no "Log On as service" privilege. You need to use LsaAddAccountRights to add such privilege to the account.

View this article please:

How To Manage User Privileges Programmatically in Windows NT

trudger
A: 

Well after a lot of testing we figured that, in most cases the problem is caused by this bug.

Anne
+1  A: 

I agree with @trudger, it's likely that the account does not have the "Log On as a service" privilege. Note that when you set the username and password through the Services management console, it automatically applies that privilege.

GuyBehindtheGuy