Question

I need to create a service remotely and would rather not break out to a command and run "sc \remotemachine create ......" and want to do it within the C# code.

However, when running the code even though the sc command works quite happily and thus is managing the remote system the ManagementScope.Connect call is throwing an exception with "The RPC server is unavailable."

A snippet of code that does this is

string machineName = "othermachine";
string path = string.Format(@"\\{0}\root\cimv2", machineName);
ManagementScope scope = new ManagementScope(path);
scope.Connect();

as this is about the first step on the journey I'm a bit stuck as to where to go next. The sc command works, so what is it doing different (other than not using .net libraries - maybe I need to hit the winapi harder?)

Thanks

Was it helpful?

Solution

After pondering this for a little while seeing the time assigned to this task being erroded away I got the old WIN32 api documentation out and [DllImport]'ed the calls I needed to do this the "old fashioned way". Being an old C dog I used to know my way around these calls, amazing how much comes back even after quite a few years of using the managed libraries.

What I needed to do was to be able to create a servcie, start it up, do useful work, stop it and delete it. The create, start, stop and delete are mechanics and I wanted to concentrate on the "do useful work" part of the activity.

I first copied the service's exe to the ADMIN$ share and verified the local path to that (with our server admins there is no telling!). To do this I call

["netapi32.dll"]NetShareGetInfo 

and then I used the following with from advapi32.dll

  • OpenSCManager
  • CreateService
  • StartService
  • OpenService (for when I want to stop and delete it - don't keep the handles open as this may take a while so cleaner to keep thngs self contained)
  • ControlService
  • QueryServiceStatus
  • CloseServiceHandle

This all works even across the VPN connection.

I can only guess that the managed api is trying to do far more than I actually need - the difference in time taken using the managed api and the Windows api is quite a lot, and with no guarantees that the managed api will get through it wasn't a suitable way forward.

OTHER TIPS

Obviously the stock code from MSDN doesn't paint the whole picture. I get the same results as you.

Check out what this guy did.

EDIT:

I believe you're trying it on a workgroup and not a domain, right? That's the trick, workgroups demand a bit more work to get through. The link above seems to have a workaround. I will try again from home tonight.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top