1

I am using MongoDb server installed on VM Ubuntu 14 on Azure, and I use this tutroial, with last version. I add the port of mongo 27017 too. And I connect to it directly and add Database with some collections. I use the mongoDb .Net Driver on VS2015 in C# with version 2.0.1 (using link) and try to connect to the Mongo Server, but the state of the server is disconnected

var client = new MongoClient("mongodb://name.cloudapp.net:27017");
var state = client.Cluster.Description.State;
MessageBox.Show(state.ToString());

I used it before the same steps and nothing happen, just I don't know where is the problem

Juste3alfaz
  • 295
  • 4
  • 21
  • 1
    [This](http://stackoverflow.com/questions/30713599/mongodb-driver-2-0-c-sharp-is-there-a-way-to-find-out-if-the-server-is-down-in) might be relevant: "mongoClient.Cluster.Description.State is not reliable". – Quantic Sep 01 '16 at 15:45
  • Maybe, but I can't add data into collection, even I ca,'t see any collections from the MongoDb server – Juste3alfaz Sep 02 '16 at 13:39
  • Adding data, and reading the state aren't conclusive to determine what an issue is, and from the looks of it, there isn't a reliable way to read the state. What exception are you getting within C#? Also, do you currently have the port/endpoint open and accepting connections in Azure? It sounds to me that it might be more of a network issue instead of a programming one. – Kevin B Burns Jun 14 '21 at 15:33

2 Answers2

6

Try this please. I think this may work. Just have to add one line to enumerate all databases.

var client = new MongoClient("mongodb://name.cloudapp.net:27017");

var databases = client.ListDatabases();

var state = client.Cluster.Description.State;
MessageBox.Show(state.ToString());

This answer explains better.

Ankit
  • 143
  • 1
  • 8
0

In fact the value in MongoClient.Cluster.Description.State is only updated after a database operation was performed, which really uses a connection. This is any kind of query to data, but not things like creation of a .net object representing a collection. So even after opening a MongoDB connection this state is still in Disconnected until you perform the first operation.

So to really verify the connection state you can use a ping (which does not update this state as ping is not a database query operation) or a simple dummy query like

var serverState = client.Cluster.Description.Servers.FirstOrDefault()?.State 
    ?? ServerState.Disconnected;
Nick
  • 472
  • 3
  • 18