1

this is my first question in here.

So I have this app that connects to a remote database using Npgsql library. I have a method that connects to the db, execute a query, and finally it closes the connection. It work fine, but the problem is that if, while the program is running but not calling the method, I disconnect the WiFi to simulate the inability to connect to the server, and then run the method, the connection method still is able to open the connection. This causes the query to get stuck. I can't seem to find a way to check if I can connect to server because, even if I disconnect the internet, the NpgsqlConnection.Open() method still opens it.

Sorry about my english

 public static NpgsqlConnection ConnectRemote()
    {
        try
        {
            remoteConnection = new NpgsqlConnection("Server = " + remoteData.server + "; " +
                                              "Port = " + remoteData.port + "; " +
                                              "User Id = " + remoteData.user + "; " +
                                              "Password = " + remoteData.password + "; " +
                                              "Database = " + remoteData.dataBase + "; ");

            remoteConnection.Open();
        }
        catch (NpgsqlException ex)
        {
            throw;
        }
        catch (Exception ex)
        {
            remoteConnection.Close();
            remoteConnection = null;
        }
        return remoteConnection;

    }

public static bool CheckRemote()
    {
            if (remoteConnection != null)
            {
                if (remoteConnection.FullState.Equals(ConnectionState.Open))
                    return true;
                return false;
            }
            return false;
    }

public bool AddNewProduct(Product product)
    {
        try
        {
            DBManager.ConnectLocal();
            DBManager.ConnectRemote();
            object[] parameters;

            if (DBManager.CheckRemote())
            {
                if (!DBManager.isSyncronized)
                {
                    DBManager.Syncronize();
                }

                parameters = new object[8];
                parameters[0] = 1;
                parameters[1] = product.id;
                parameters[2] = product.description;
                parameters[3] = (decimal)product.salePrice;
                parameters[4] = (decimal)product.cost;
                parameters[5] = product.minStock;
                parameters[6] = product.providerName;
                parameters[7] = product.category;
                DBManager.RunFunction(DBManager.remoteConnection, DBProcedures.createProduct, parameters);
            }
            else
            {
                string sql = "select * from createproduct(1, " + product.id + ", '" + product.description + "', " + (decimal)product.salePrice + ", " 
                    + (decimal)product.cost + ", " + product.minStock + ", '" + product.providerName + "', '" + product.category + "'); ";
                parameters = new object[1];
                parameters[0] = sql;
                DBManager.RunFunction(DBManager.localConnection, "addsync", parameters);

                DBManager.isSyncronized = false;

            }

            parameters = new object[6];
            parameters[0] = product.description;
            parameters[1] = (decimal)product.salePrice;
            parameters[2] = (decimal)product.cost;
            parameters[3] = product.minStock;
            parameters[4] = product.providerName;
            parameters[5] = product.category;

            DataTable result = DBManager.RunFunction(DBManager.localConnection, DBProcedures.createProduct, parameters);
            DBManager.DisconnectLocal();
            DBManager.DisconnectRemote();
            return true;
        }
        catch (Npgsql.NpgsqlException ex)
        {
            return false;
        }           
    }
1
  • 1
    What you're asking isn't entirely clear, but you may simply be seeing the connection pool at work. By default, when you close a connection Npgsql actually keeps it open internally. When you next open a connection, it will reuse the previous connection instead of opening a new one - this is very important for performance. So you have a connection in the pool, Open() doesn't really do anything, but if your network is down your query will fail. Dec 1, 2017 at 4:06

1 Answer 1

3

A few things -- one unrelated, and two related. I am hopeful that some combination of these will help.

  1. First, the unrelated comment. The NpgSqlStringBuilder class is a nice tool to help demystify the connection strings. I realize yours works, but as you have to make edits (as I will suggest in a minute), I find it much easier to use than navigating String.Format, just as Query Parameters are easier (on top of being more secure) than trying to string.Format your way through passing arguments to a query. Also, declare the ApplicationName in your connection string to help diagnose what exactly is happening on the server, like you will read in the next comment.

  2. If you are using connection pooling, When a connection is closed, I don't think it's really closed -- not even on the database. If you open server admin, you will see what I mean -- it kind of dangles out there, waiting to be reused. Try setting pooled=false in your connection string to ensure that when you close a connection you really close it.

  3. If this doesn't work, try a trivial query. The cost will be minimal in cases where you don't need it and will undoubtedly fix your use case when you do need it.

All three suggestions are reflected here:

public static NpgsqlConnection ConnectRemote()
{
    NpgsqlConnectionStringBuilder sb = new NpgsqlConnectionStringBuilder();
    sb.ApplicationName = "Connection Tester";
    sb.Host = remoteData.server;
    sb.Port = remoteData.port;
    sb.Username = remoteData.user;
    sb.Password = remoteData.password;
    sb.Database = remoteData.database;
    sb.Pooling = false;

    remoteConnection = new NpgsqlConnection(sb.ToString());

    try
    {
        remoteConnection.Open();
        NpgSqlCommand test = new NpgSqlCommand("select 1", remoteConnection);
        test.ExecuteScalar();
    }
    catch (NpgsqlException ex)
    {
       throw;
    }
    catch (Exception ex)
    {
       remoteConnection.Close();
       remoteConnection = null;
    }
    return remoteConnection;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.