I'm using the following code to define a service dependency on SQL Server:
serviceInstaller.StartType = ServiceStartMode.Automatic;
serviceInstaller.ServicesDependedOn = new[] { "MSSQLSERVER" };
Installers.Add(serviceInstaller);
Installers.Add(processInstaller);
This works in two machines, one with SQL Server and the other with SQL Server Express. But when I installed the service in the clients server, it failed because the SQL Server Express service name was different (SQLSERVEREXPRESS). Is there any way of defining a dependency that works in both situations? Thanks.
You need to use the proper service name. The SQL service name is MSSQLSERVER for default instances, SQLSERVEREXPRESS for (some) Express instances and MSSQL$<instancename>
for a named instance. Since the name is basically dynamic the best option is to enumerate the SQL Server services and pick the right name, or prompt the user if multiple choices are present.
Unfortunately I am not aware of any API to enumerate the installed SQL Server instances. Even MS support resorts to querying the registry:
Q. How do I determine how many instances of SQL Server are installed on a computer?
A: The names of all SQL Server instances on a computer can be found from the InstalledInstances value which is located under the following registry key:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server
Here is an elaboration on what Remus Rusanu proposed:
//Source: https://stackoverflow.com/a/7139986/16911
//Get all installed named instances.
var localMachine = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
var rk = localMachine.OpenSubKey("SOFTWARE\\Microsoft\\Microsoft SQL Server");
var instances = (String[])rk.GetValue("InstalledInstances");
List<String> sqlServices = instances.Select(x => "MSSQL$" + x).ToList();
//Add SQLSERVEREXPRESS and MSSQLSERVER, if they exist.
if(DoesServiceExist("SQLSERVEREXPRESS")) {
sqlServices.Add("SQLSERVEREXPRESS");
}
if(DoesServiceExist("MSSQLSERVER")) {
sqlServices.Add("MSSQLSERVER");
}
service.ServicesDependedOn = sqlServices.ToArray();
I did not have an opportunity to fully test non-named instances, or to test differences between x64/x86, etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With