.NET driver connection

Hello everyone, i’m new to MongoDB.
I’m writing a new application in my desktop, but i cannot undestand how to check if the client is connected to the server before to make any query.
If i stop the service in windows, in the shell the connection to “mongo” fail.
So in the driver how can check this ? Thanks a lot.

        private void Init()
         {                    
                client = new MongoClient("mongodb://localhost:27017");            
         }    
        private bool CheckConnectionToBatabase()
        {  
           //verify is the server is up and running and if the client is connected to it?
            var t = client.GetDatabase("prodcuts");
            //return true or false
        } 

        private void InsertDocument(BsonDocument document)
        {
            if(CheckConnectionToBatabase())
                 collection.InsertOne(document);
        }

        private void MongoDb_Load(object sender, EventArgs e)
        {
            Init();
            GetDatabase("shop");
            GetCollection("products");
        }
1 Like

I think you can use the Ping method, something like

var client = new MongoClient(connectionString);
var server = client.GetServer();
server.Ping();

Hi Robert and thanks for your answer. Unfortunately the GetServer() method is not available on the last release. So i figured out of the problem with another approach.
I test the connection using stop and start service on the shell, and i see that if the server goes down, the client is able to reconnect automatically.

So, i share my solution to test if a valid connection is ready before sent a “crud” command :

    private bool CheckConnectionToBatabase()
            {
                var database = new BsonDocument();
                var timeoutCancellationTokenSource = new CancellationTokenSource(TimeSpan.FromMilliseconds(2000)); //2000ms timeout token
                try
                {
                    var databases = client.ListDatabasesAsync(timeoutCancellationTokenSource.Token).Result;
                    databases.MoveNextAsync(); // Force MongoDB to connect to the database.
                    if (client.Cluster.Description.State == ClusterState.Connected)
                    {
                        // Database is connected.
                        return true;
                    }
                    else
                        return false;
                }
                catch(Exception e)
                {
                    return false;
                }          
            }
1 Like