question

DarrylHoar-5879 avatar image
0 Votes"
DarrylHoar-5879 asked ErlandSommarskog commented

How to validate a user entered Sql Instance name entered in c#

Service app project in Visual Studio Pro 2019. Using .NET Framework 4 Client Profile and C#

The user enters the sql instance name in the config file using key/pair value of SQL_INSTANCE "SQLEXPRESS".
Now, the user can set the SQL_INSTANCE to something else if required.

I have googled and most of the result discuss using SQL Configuration manager to see SQL_INSTANCE.
I need to be able to programmatically check it in the Service app to verify if the user entered Instance is
valid. How do I do that ? Didn't see any discussion on how to accomplish this.

Thanks.

sql-server-generaldotnet-csharp
· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

@DarrylHoar-5879, is any update, do you have time to check if my answer works for you?

0 Votes 0 ·
JackJJun-MSFT avatar image
0 Votes"
JackJJun-MSFT answered DarrylHoar-5879 commented

@DarrylHoar-5879, Welcome to Microsoft Q&A. you could get the instance name from the registry then you could validate the user;s input.

Here is a code example you could refer to:

  private void button1_Click(object sender, EventArgs e)
         {
             RegistryView registryView = Environment.Is64BitOperatingSystem ? RegistryView.Registry64 : RegistryView.Registry32;
             List<string> list = new List<string>();
             using (RegistryKey hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, registryView))
             {
                 RegistryKey instanceKey = hklm.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SQL Server\Instance Names\SQL", false);
                 if (instanceKey != null)
                 {
                     foreach (var instanceName in instanceKey.GetValueNames())
                     {
                         Console.WriteLine(instanceName);
                         list.Add(instanceName);
                     }
                 }
             }
             string instancetext = textBox1.Text;
             if(list.Contains(instancetext))
             {
                 MessageBox.Show("The instance name is correct");
             }
             else
             {
                 MessageBox.Show("The instance name is wrong");
             }
         }

Best Regards,
Jack


If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Jack,
I have seen this solution through googling. I was hoping for an approach that let me verify SQL Instance name when SQL is installed local or
when it is on another server. Ie, the application can work with a locally installed SQL Server instance as well as a SQL Server installed on a network server.

The connect/fail approach gives me pause as a connection string contains many elements (including SQL Instance name) and a failure could be due to
something other than an invalid SQL Instance name. Some of the other elements are not easy to test for correctness.

Thanks.

0 Votes 0 ·
OlafHelper-2800 avatar image
0 Votes"
OlafHelper-2800 answered

I need to be able to programmatically check it in the Service app to verify if the user entered Instance is valid.

Also for remote SQL Server (instances)? Open a SQL Server connection to the entered instance name and if it fails you know the name isn't valid. That's the way most application works, like SSMS.
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

TomPhillips-1744 avatar image
0 Votes"
TomPhillips-1744 answered ErlandSommarskog commented

There is no way to validate the connection string without attempting to connect to the server.

· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

If it is a matter of validating a local instance, reading the registry as Jack suggests should work, I think. But validating a remote instance requires a connection attempt in some form. The original post is not wholly clear, but I get the feeling that it is a matter of validing a local instance.

0 Votes 0 ·
karenpayneoregon avatar image
1 Vote"
karenpayneoregon answered

You could do a brute force connect with a time-out.

Setup a CancellationTokenSource, here to time-out in two seconds

 private static int _timeOut = 2;
 private CancellationTokenSource _cancellationTokenSource =
     new CancellationTokenSource(TimeSpan.FromSeconds(_timeOut));

Method to test connection

 public class Operations
 {
     public static async Task<(bool success, Exception exception)> Connect(string connectionString, CancellationToken cancellationToken)
     {
    
         try
         {
             await using var cn = new SqlConnection(connectionString);
             await cn.OpenAsync(cancellationToken);
             return (true, null);
         }
         catch (Exception e)
         {
             return (false, e);
         }
    
     }
 }


Call it and deconstruct the results

 var (success, exception) = await Operations.Connect("user connection string goes here",_cancellationTokenSource.Token);

Side note, there is always a permission issue, connection string may be good but not assessible to the user.



5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.