MongoDB get server - c#

I try to connect to server and get database. It run properly but it VS2013 show me a warning :
Warning 1 'MongoDB.Driver.MongoClientExtensions.GetServer(MongoDB.Driver.MongoClient)' is obsolete: 'Use the new API instead.
string connectionString = "mongodb://localhost:27017";
MongoClientSettings settings = MongoClientSettings.FromUrl(new MongoUrl(connectionString));
MongoClient mongoClient = new MongoClient(settings);
var server = mongoClient.GetServer();
var db = server.GetDatabase("bookstore");
var bookCollection = db.GetCollection<Book>("Book");
Can someone help me solve this ? Tks for reading.

The MongoServer class was deprecated in version 2.0.0 (see here). You can call GetDatabase() directly on the MongoClient object:
MongoClient mongoClient = new MongoClient(settings);
var db = mongoClient.GetDatabase("bookstore");
More documentation about connecting to the MongoDB server, retrieving a database, etc. can be found in the reference documentation.

I changed my code to following:
var mongoUrl = new MongoUrl(connectionString);
var mongoClient = new MongoClient(mongoUrl);
MongoServer server = new MongoServer(MongoServerSettings.FromClientSettings(mongoClient.Settings));

The example code from #Robby works, but it doesn't return what your code is expecting; it returns Interface objects. The C# driver was updated to utilize Interface methods, as well as a number of asynchronous functions, so updating your code is probably a good idea.
The new way to get a database is -- well, you don't get a database anymore. You get an IMongoDatabase which is an interface to the database. Also, you should not work with MongoCollections anymore (from the MongoDatabase object), when you get an IMongoDatabase you will work with an IMongoCollection. Refactoring? You bet! But it's worth it.
I would also recommend putting your default database in the Mongo URL formatted connection strings. That way you can keep hard-coded constants, such as the database name, out of your code.
// Get your connection string -- use the URL format as in example below:
// name="MongoConnectionStr" connectionString="mongodb://localhost/bookstore"
var connectionString = ConfigurationManager.ConnectionStrings["MongoConnectionStr"].ConnectionString;
var mongoUrl = MongoUrl.Create(connectionString);
var client = new MongoClient(connectionString);
// Use the Mongo URL to avoid hard-coding the database name.
var db = new MongoClient(mongoUrl).GetDatabase(mongoUrl.DatabaseName);
// books below is an IMongoCollection
var books = db.GetCollection<Book>("Books");

Related

Authenticate User on MongoDB with .NET Driver 2.4

The following code works as it should do, if the server is running and if the usename and password are correct. However, if i give a wrong username or password, it does not give me feedback, but only runs into a timeout when calling the Count method.
MongoClientSettings setts = new MongoClientSettings()
{
Server = new MongoServerAddress("127.0.0.1", 27017),
Credentials = new MongoCredential[] { MongoCredential.CreateCredential("TestDatabase", "username", "password") }
};
this.client = new MongoClient(setts);
this.client.Cluster.DescriptionChanged += this.ClusterDescriptionChanged;
var database = this.client.GetDatabase("TestDatabase");
var collection = database.GetCollection<BsonDocument>("SimpleCollection");
var count = collection.Count(MongoDB.Driver.FilterDefinition<BsonDocument>.Empty);
How do i get error messages from the driver and how can i check if it's the connection, the user or the password that does not fit?
PS: The driver API has changed a lot since 2.0 in Jan.2016, which means that most webtutorials and posts on this site no longer work for the current version.
Once you get the client, you can check if the connection is successful
var server = client.GetServer();
server.Ping();
Also it is always a good idea to enclose your code in a try catch with timeout exception because that is expected.
for more info on this you can refer MongoDB C# Driver check Authentication status & Role

Connect to DocumentDB using MongoDb API

I have following problem
While I am trying to connect to the DocumentDB database using MongoDb API:
var cstring = "mongodb://textadmin:<MY VERY SECRET PASSWORD>#<MY SERVER>.documents.azure.com:10250/?ssl=true"
var client = new MongoDB.Driver.MongoClient(cstring)
var server = client.GetServer()
server.Ping()
I have the following error:
Authentication failed because the remote party has closed the transport stream
Any ideas what to change in the code (or in the server settings perhaps)?
You need to set EnabledSslProtocols to TLS12 to be able to connect to DocumentDB using MongoDB API. By default, the Mongo C# driver does not use TLS1.2 causing the connection to fail during SSL handshake.
Sample Code:
MongoClientSettings settings = new MongoClientSettings();
settings.Server = new MongoServerAddress(host, 10250);
settings.UseSsl = true;
settings.SslSettings = new SslSettings();
settings.SslSettings.EnabledSslProtocols = SslProtocols.Tls12;
MongoIdentity identity = new MongoInternalIdentity(dbName, userName);
MongoIdentityEvidence evidence = new PasswordEvidence(password);
settings.Credentials = new List<MongoCredential>()
{
new MongoCredential("SCRAM-SHA-1", identity, evidence)
};
MongoClient client = new MongoClient(settings);
Reference: https://azure.microsoft.com/en-us/documentation/articles/documentdb-mongodb-samples/

MongoDB getserver is not available anymore, how can I connect to my database

I was trying to connect to mongoDB database but I figured out that gerserver function is not available anymore. Here is a part of my code that achieves this.I am getting error while I am tryng to create a database because I am trying to convert it implicitly(MongoDatabase db=client.GetDatabase("test")
string connectionString = "Server=localhost:27017";
Console.WriteLine("Connection MongoDB");
MongoClient client = new MongoClient(connectionString);
//MongoServer server = client.GetServer()
MongoDatabase db = client.GetDatabase("test");
The MongoClient constructor takes a MongoDB connection URI, not a .Net style connection string.
So it should be:
MongoClient client = new MongoClient("mongodb://localhost:27017");
IMongoDatabase db = client.GetDatabase("test");
Note that I also changed the type of db to IMongoDatabase as that's what's returned by GetDatabase.

Connection to a query router (mongos) from C# and list databases

I nee to connect to a mongo and run a commands.
I'm am connecting using the following piece of code. I want to test weather I am connecting by listing the databases.
MongoClient client = new MongoClient("mongodb://127.0.0.1:27017");
client.ListDatabases();
If I debug and click on the second line I cannot see the names of the databases. How can I print the names of the databases to screen to confirm I am connected to mongo.
You need to specify credentials in the Connection String. Couple ways you can do this:
var connectionString = "mongodb://user1:password1#127.0.0.1:27017";
Is the format expected, you will have to supply the username and password yourself, these are just placeholders.
Or you can create a MongoCredentials object and use that instead of a connection string (probably a bit cleaner this way, and allows more configuration if you look deeper into the object documentation)
var credential = MongoCredential.CreateMongoCRCredential("test", "user1", "password1");
var settings = new MongoClientSettings
{
Credentials = new[] { credential }
};
var mongoClient = new MongoClient(settings);
Both of these examples are found on MongoDB's documentation site
Try GetDatabaseNames() method and also assign the result to a variable. So that you can inspect it at breakpoint like
MongoClient client = new MongoClient("mongodb://127.0.0.1:27017/");
var databaseNames = client.GetDatabaseNames();
ListDatabases returns an IAsyncCursor so try the following:
var client = new MongoClient(<CONNECTION STRING>);
var cursor = client.ListDatabases();
cursor.ForEachAsync(db => Console.WriteLine(((BsonString)db["name"]).Value));

Uploading data into Mongolab database

I am trying to insert elements into a MongoLab database (Sandbox plan) using C# (by parsing a xml file, but that is not the relevant part).
var connectionString = "mongodb://user:pass#ds011111.mongolab.com:11111/db";
var server = client.GetServer();
var database = server.GetDatabase("mydb");
var elementCollection = database.GetCollection<Entity>("entities");
XmlDocument doc = new XmlDocument();
doc.LoadXml(elementxml);
XmlNodeList elementList = doc.GetElementsByTagName("element");
foreach (XmlNode element in elementList)
{
var t = new Entity();
t.Name = element.FirstChild.InnerText;
elementCollection.Insert(t); // this causes the error below
}
This is the message I get:
WriteConcern detected an error 'not authorized for insert on mydb.entities'. (Response
was { "err" : "not authorized for insert on mydb.entities", "code" : 16544, "n" : 0,
"lastOp" : { "$timestamp" : NumberLong(0) }, "connectionId" : 33932414, "ok" : 1.0 }).
If I run the same code on localhost, everything works as intended
If I insert an element using mongo/shell I get Cannot use commands write mode, degrading to compatability mode, but it works
Does this mean I cannot populate my mongolab database with data (from C#) because I do not have the right permissions as a Sandbox user? If that is the case, what are my options?
The problem seems to be that you're authenticating to the "db" database but trying to use the "mydb" database. Except for specially-privileged/admin users, most users only have access to one database, hence the not authorized error. We run all our databases with authentication on, while the MongoDB defaults, which you're likely using locally, require no authentication; that's why you're not seeing the issue locally.
You should be grabbing the DB to be used from the URI. Here's an example from our Language Center.
// Standard URI format: mongodb://[dbuser:dbpassword#]host:port/dbname
String uri = "mongodb://user:pass#host:port/db";
MongoUrl url = new MongoUrl(uri);
MongoClient client = new MongoClient(url);
MongoServer server = client.GetServer();
MongoDatabase db = server.GetDatabase(url.DatabaseName);
If that doesn't sort you out, try our connectivity troubleshooting guide. In particular, the next thing I'd look at is whether you're using the right credentials (see the section entitled "Check your database credentials").
Finally, please don't hesitate to contact us as support#mongolab.com if you continue to have issues or have any other questions.

Categories

Resources