C#
Scenarios
DDS allows you to perform data operations using C#. You can connect to a DB instance through an SSL connection or a non-SSL connection. SSL connections provide stronger security.
By default, SSL is disabled for new DDS instances. For details about how to enable SSL, see Configuring SSL.
This section describes how to connect to a single node instance using C#.
Prerequisites
- Ensure that the ECS can communicate with the DDS instance. To test the connectivity to the instance's IP address and port, run the curl command:
shell
curl ip:port
If the message "It looks like you are trying to access MongoDB over HTTP on the native driver port." is displayed, the ECS and DDS instance can communicate with each other.
- If SSL is enabled, you need to download the root certificate and upload it to the ECS.
Configuring the Environment and Obtaining the Driver
- Installing .NET SDK: Ensure that .NET SDK is available in your environment. You can download it from https://dotnet.microsoft.com/download.
- Creating a project: Open the CLI or command prompt and create a .NET console application.
dotnet new console -n DDSExample cd DDSExample
- Adding the MongoDB C# driver: Add the MongoDB C# driver to your project using NuGet.
dotnet add package MongoDB.Driver
Enabling and Disabling SSL
using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
public class MongoDBSecureWriter
{
public static async Task Main()
{
var connectionString = "mongodb://rwuser:rwuserpassword@ip:port/{mydb}?authSource=admin&directConnection=true";
var caCertPath = "/path/to/certs/ca.crt";
var collectionName = "testCollection";
try
{
var client = CreateSecureClient(connectionString, caCertPath);
var database = client.GetDatabase("mydatabase");
var collection = database.GetCollection<BsonDocument>(collectionName);
var document = new BsonDocument
{
{ "name", "Secure Test" },
{ "value", 42 },
{ "timestamp", DateTime.UtcNow }
};
await collection.InsertOneAsync(document);
Console.WriteLine($"Insert doc ID: {document["_id"]}");
// Verify the write operation.
var filter = Builders<BsonDocument>.Filter.Eq("_id", document["_id"]);
var result = await collection.Find(filter).FirstOrDefaultAsync();
Console.WriteLine($"result: {(result != null ? "success" : "fail")}");
}
catch (Exception ex)
{
Console.WriteLine($"Fail: {ex.Message}");
if (ex.InnerException != null)
{
Console.WriteLine($"Exception: {ex.InnerException.Message}");
}
}
}
private static MongoClient CreateSecureClient(string connectionString, string caCertPath)
{
var caCert = new X509Certificate2(caCertPath);
var settings = MongoClientSettings.FromConnectionString(connectionString);
settings.SslSettings = new SslSettings
{
CheckCertificateRevocation = false,
ClientCertificates = new[] { caCert }
};
settings.UseTls = true;
settings.AllowInsecureTls = true;
settings.MaxConnectionPoolSize = 100;
settings.MinConnectionPoolSize = 10;
return new MongoClient(settings);
}
} using MongoDB.Driver;
using MongoDB.Bson;
using System;
class Program
{
static void Main(string[] args)
{
// Replace <YourConnectionString> with your MongoDB connection string
var connectionString = "mongodb://rwuser:rwuserpassword@ip:port/{mydb}?authSource=admin&directConnection=true";
// Create a MongoClient object
var client = new MongoClient(connectionString);
// Get a reference to the database
var database = client.GetDatabase("testDatabase");
// Get a reference to a collection
var collection = database.GetCollection<BsonDocument>("testCollection");
// Create a sample document
var document = new BsonDocument
{
{ "name", "DDS" },
{ "type", "Database" },
{ "count", 1 },
{ "versions", new BsonArray { "v3.4", "v4.0", "v4.2" } },
{ "info", new BsonDocument { { "x", 203 }, { "y", 102 } } }
};
// Insert the document into the collection
collection.InsertOne(document);
Console.WriteLine("Document inserted successfully!");
}
}
- The authentication database in the URL must be admin. That means setting authSource to admin.
- Change the authentication database of the rwuser user to admin, and then switch to the service database after authentication.
Running the Program
Run the following command on the CLI or command prompt to run the program:
dotnet run
Feedback
Was this page helpful?
Provide feedbackThank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot