private MongoDatabase ConnectMongoDatabaseAsync() { try { // if the underlying server connection is not connected... if (MongoServerConnection.State == MongoServerState.Disconnected) { // connect to the server asynchronously MongoServerConnection.ConnectAsyncDelegate(serverConnection_AsyncConnectionCompleted); // but wait for the connected event call back to notify us that the server is connected // before proceeding _serverConnectionResetEvent.WaitOne(); _serverConnectionResetEvent.Reset(); } else { while (MongoServerConnection.State == MongoServerState.Disconnected) { ; // spin until the server gets connected // this case should only happen when a server connection asynchronously is connecting, // and then a DatabaseConnection is created using it } } // if DatabaseConnection failed to connect this will raise an exception return(MongoServerConnection.GetDatabase(_dbName, WriteConcern.Acknowledged)); } catch (Exception ex) { // probably illegal conn string or db name throw new MongoDatabaseConnectionException("Error connecting to " + _dbName + " database", ex); } }
// Define the indexer, which will allow client code // to use [] notation on the class instance itself. public MongoCollection this[string collectionName] { get { // This indexer is very simple, and just returns // the corresponding collection from the internal array. return(MongoServerConnection.GetDatabase(Db.Name, WriteConcern.Acknowledged).GetCollection(collectionName)); } }
/// <summary> /// Synchronous connection /// </summary> public void Connect() { try { Db = null; _databaseConnectionResetEvent.Reset(); // if the underlying MongoServerConnection is not connected, connect it since we // depend on it to execute queries if (MongoServerConnection.State == MongoServerState.Disconnected) { MongoServerConnection.Connect(); } // if the database already exists than it is fetched otherwise created Db = MongoServerConnection.GetDatabase(_dbName, WriteConcern.Acknowledged); } catch (Exception ex) { // TODO: add ex handling! throw ex; } }