views:

635

answers:

2

Is there a way to set a dependency of one "myWindowsService" to another service running on the same machine such as "SqlService"?

The prob is if you dont know the name of the "sql service" where "myWindowsService" will be installed, but my service depends on that the sql is already running..

thanx

A: 

Edit: Didn't read the question correctly.

A workaround (not the most elegant solution) is to enumerate all services against a known whitelist with known instance names.


Using ManagementObject you could set dependencies (but you have to know the name of the service):

    bool SetServiceDependencies(string serviceName, string[] dependencies)
    {
        try
        {
            string objPath = string.Format("Win32_Service.Name='{0}'", serviceName);
            //Uses lazy initialization
            ManagementObject mmo = new ManagementObject(new ManagementPath(objPath));
            //Get properties to check if object is valid, if not then it throws a ManagementException
            PropertyDataCollection pc = mmo.Properties;
        }
        catch (ManagementException me)
        {   //Handle errors
            if (me.ErrorCode == ManagementStatus.NotFound) {
                //Service not found
            }
            return false;
        }
        try
        {   
            object[] wmiParams = new object[11];    //parameters for Win32_Service mmo object Change-parameters
            wmiParams[10] = dependencies;

            //Should we remove dependencies, use array containging 1 empty string
            if (dependencies == null || dependencies.Length == 0)
            {
                wmiParams[10] = new string[] { "" };
            }

            //Change dependencies
            string returnStatus = mWmiService.InvokeMethod("Change", wmiParams).ToString();
        }
        catch (Exception)
        {
            return false;
        }
        return true;
    }
MatteKarla
A: 

If you are using

sc create <service>

syntax, you can supply other services to this which will make your installed service depend on that service being started.

sc create <service> depend= mssqlserver

This can also be done automatically if you are using the ServiceInstaller classes. There is an area in the properties for that controller to define startup dependencies.

I know you said you might not know the name of the other services, but changing the dependencies is quite simple also.

neouser99