0

I recently converted a Delphi app to C#, and I'm having an issue with an SQL connection. For some reason, when calling the CheckConnection function (shown below), IF my connection string has empty parameters, the connection is still able to .Open() without errors. Why is this? I feel like my CheckConnection function has an issue, or maybe I'm not understanding how .Open() actually works.

How it's set up - There are some textboxes that contain the hostname, user, etc. which are used as the parameters for the the connection string. Everything works fine when those are filled out correctly, but when the parameters (aka the textboxes) are all left blank, the connection still opens.

String hostname, user, password, database, protocol, query;
string connString;
IDbConnection SqlConn;
DbProviderFactory factory;    

    public void SetConnectionParams()
    {
        hostname = ServerTextBox.Text.Trim();
        port = StrToIntDef(PortTextBox.Text, 3306);
        user = UserIDTextBox.Text;
        password = PasswordTextBox.Text;
        database = DBTextBox.Text;
        protocol = ProtocolTextBox.Text; //MIGHT not need

        GetConnectionString(); //Get the correct connection string
    } 

    //Gets the connection string from app.config
    //The parameters for the string are all set via textboxes in diff. part of code
    public void GetConnectionString()
    {
        if (MySqlRB.IsChecked == true) //Sets up connection for MySQL
        {
            var cs = ConfigurationManager.ConnectionStrings["MySQL"];
            connString = ConfigurationManager.ConnectionStrings["MySQL"].ToString();
            factory = DbProviderFactories.GetFactory(cs.ProviderName);
            connString = String.Format(connString, hostname, port, database, user, password);
        }
        else //Sets up connection for MS SQL
        {
            if (WindowsAuth.IsChecked == true) //If windows authentication checkbox is checked
            {
                var cs = ConfigurationManager.ConnectionStrings["MSSQL_WA"];
                connString = ConfigurationManager.ConnectionStrings["MSSQL_WA"].ToString();
                factory = DbProviderFactories.GetFactory(cs.ProviderName);
                connString = string.Format(connString, hostname, database);
            }
            else //don't use windows authentication
            {
                var cs = ConfigurationManager.ConnectionStrings["MSSQL"];
                connString = ConfigurationManager.ConnectionStrings["MSSQL"].ToString();
                factory = DbProviderFactories.GetFactory(cs.ProviderName);
                connString = string.Format(connString, hostname, database, user, password);
            }
        }
    }

    //Supposed to check if the connection works or not
    //This is working even if the connection string has empty parameters
    public Boolean CheckConnection(bool check)
    {
        try
        {
            if (!CloseFirst && (SqlConn.State != System.Data.ConnectionState.Open))
            {
                return false;
            }
            else
            {
                using (SqlConn = factory.CreateConnection()) //make the connection
                {
                    SqlConn.Close(); //make sure it's closed first just in case 
                    SqlConn.ConnectionString = connString;
                    SqlConn.Open(); // Open the connection

                    if (SqlConn.State == System.Data.ConnectionState.Open)
                    {
                        SqlConn.Close();
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }
            }
        }
        catch
        {
            return false;
        }
    }

Example: Here's a connection string that's in my app.config for a sql server string:

<add name="MSSQL" providerName="System.Data.SqlClient" 
          connectionString="Data Source={0}; Initial Catalog={1}; User={2}; Password={3};" />

When debugging through the program, if I don't set any of the parameters, the string turns out like this:

connString = "Data Source=; Initial Catalog=; User=; Password=;"

That shouldn't be able to open right? It does though, and only when using SQL Server it seems, MySQL throws an error properly.

Edit:

Okay, turns out an error is not being thrown only when I use SQL Server windows authentication with this connection string:

<add name="MSSQL_WA" providerName="System.Data.SqlClient" connectionString="Data Source={0}; Initial Catalog={1}; Integrated Security=SSPI;"/>

Debugging through, the Data Source and Initial Catalog are empty, but the connection still opens. Not sure why this is?

pfinferno
  • 1,779
  • 3
  • 34
  • 62
  • Can you add an example of your string that has empty parameters, or do you mean an empty string ""? – Alex K. Apr 18 '16 at 11:53
  • Done! And yeah, empty parameters, the string is not empty itself. – pfinferno Apr 18 '16 at 11:57
  • in connString = String.Format(connString, hostname, port, database, user, password); .. where are hostname, port, database and user coming from, you dont show them being set to anything – BugFinder Apr 18 '16 at 11:59
  • Sorry, I put it in a comment in the code, should've put it more clearly. They are being set by textboxes. I'll update question. – pfinferno Apr 18 '16 at 12:03
  • According to [How to check if connection string is valid?](http://stackoverflow.com/questions/434864/how-to-check-if-connection-string-is-valid), `Open` should throw if the connstring is invalid. – stuartd Apr 18 '16 at 12:07
  • Hmm that's what I thought. In fact, that's the question I think I was basing this code off of. I've gone through line by line in the debugger, making sure the connection string does in fact have empty parameters. The connection is still able to open. – pfinferno Apr 18 '16 at 12:09
  • Wait, It's not throwing the error only when I'm checking a "Windows Authentication" box. If the data source and initial catalog are empty, but integrated security isn't, will it still open? – pfinferno Apr 18 '16 at 12:34
  • 2
    `new SqlConnection("Integrated Security=True").Open();` works for me here, possibly because I have a default instance (i.e. '(local)') – stuartd Apr 18 '16 at 12:47
  • Hmm, so I guess even if the host and initial catalog aren't set, but you have a default instance, it will work. – pfinferno Apr 18 '16 at 12:49

0 Answers0