Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I define a dependency on SQL Server in a windows service that works with SQL Server Express

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.

like image 337
jassuncao Avatar asked Jun 15 '09 10:06

jassuncao


2 Answers

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

like image 104
Remus Rusanu Avatar answered Sep 21 '22 16:09

Remus Rusanu


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.

like image 28
AaronSieb Avatar answered Sep 18 '22 16:09

AaronSieb