How can I determine the dependency on SQL Server in a Windows service that works with SQL Server Express

I use the following code to determine the service dependency on SQL Server:

serviceInstaller.StartType = ServiceStartMode.Automatic; serviceInstaller.ServicesDependedOn = new[] { "MSSQLSERVER" }; Installers.Add(serviceInstaller); Installers.Add(processInstaller); 

It runs on two machines, one with SQL Server and the other with SQL Server Express. But when I installed the service on the client server, it failed because the SQL Server Express service name was different (SQLSERVEREXPRESS). Is there a way to determine the dependency that works in both situations? Thank you

+7
c # windows-services
source share
2 answers

You need to use the correct service name. The SQL service name is MSSQLSERVER for default instances, SQLSERVEREXPRESS for (some) Express instances, and MSSQL$<instancename> for the named instance. Because the name is mostly dynamic, the best option is to list the SQL Server services and select the correct name or query the user if there are several options.

Unfortunately, I do not know any API for listing installed instances of SQL Server. Even MS Support resorts to registry queries :

Q. How to determine how many instances of SQL Server are installed on a computer?

A: the names of all SQL Server instances on the computer can be found from the InstalledInstances value which is located under the following registry key: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server

+11
source share

Here is a study of what Remus suggested to Rusan :

 //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 was not able to fully test unnamed instances or check the differences between x64 / x86, etc.

0
source share

All Articles