The code below works except for what looks like a keep alive login in my MongoDB logs after I execute code to create a Database, Collection and a user within MongoDB. The login is with the newly created user account, and it does not stop until I stop the App Service that ran created the user. If the user is deleted from Mongo, then the logging goes into overdrive with user not found errors and eats up over 32Gb of disk space per day. I am running the code below on .Net 4.7.2/C# using the latest Mongo.Driver package version 2.16.1. At first, I thought it was trash collection issue with my method but then I set all the objects to null at the end to the method and that still did not affect it. Is there a command I am missing to tell the Mongo Driver to release the thread to the database? I would appreciate any help.
Source code
public async Task<IHttpActionResult> MongoCreateAsync(int companyId, string userEmail)
{
string MongoDB = "";
try
{
string databaseName = "Tester" + companyId.ToString();
//Name Validations.
if (!string.IsNullOrEmpty(databaseName))
{
string ErrorString = "";
if (MongoUtility.MongoDatabaseNameValidation(databaseName, ref ErrorString))
{
//********************************************************************************
// Create
//********************************************************************************
var mail = new MailAddress(userEmail);
string username = CryptoUtility.GenerateUserName();
string password = CryptoUtility.GeneratePassword();
//
//Create Catalog Database and User Instance in MongoDB.
//
var connectionString = CryptoUtility.GetDecryptedString(System.Configuration.ConfigurationManager.ConnectionStrings["MongoConnectionString"].ConnectionString);
MongoClient mongoClient = new MongoClient(connectionString);
//Creates the new Catalog database in Mongo.
var db = mongoClient.GetDatabase(databaseName);
//Create User in the new database in Mongo.
var user = new BsonDocument {
{ "createUser", username },
{ "pwd", password },
{
"roles", new BsonArray
{
new BsonDocument { { "role", "dbOwner" }, { "db", databaseName } },
new BsonDocument { { "role", "read" }, { "db", databaseName } },
new BsonDocument { { "role", "readWrite" }, { "db", databaseName } }
}
}
};
await db.RunCommandAsync<BsonDocument>(user);
//Create connection string to the new database using the created user and
//encrypt the connection string for storage in the Catalog table in SQL.
var connectionString2 = $"mongodb://" + username + ":" + password + "@" + CryptoUtility.GetDecryptedString(ConfigurationManager.AppSettings["MongoPath"]) + "/" + databaseName + "?authSource=" + databaseName + "&readPreference=primary&appname=MongoDB%20Compass%20Community&ssl=false";
MongoDB = CryptoUtility.GetEncryptedString(connectionString2);
/// This code adds a new collection to the MongoDB using the created connection string.
var noSqlDataContext = new MongoDataContext(CryptoUtility.GetDecryptedString(MongoDB), databaseName);
string collectionName = $"CreationInfo";
IGenericNoSqlRepository<CreationInfo> _newRepository = new MongoDbGenericRepository<CreationInfo>(noSqlDataContext, collectionName);
CreationInfo datalist = new CreationInfo
{
CatalogName = databaseName,
CatalogDesc = "Initial Creation",
CompanyId = companyId,
CreatedBy = userEmail
};
await _newRepository.SaveAsync(datalist);
noSqlDataContext = null;
db = null;
mongoClient = null;
}
}
}
catch (Exception ex)
{
Trace.TraceError(ex.ToString());
}
return Ok(MongoDB);
}
public class MongoDataContext: IDisposable
{
private bool disposed = false;
public MongoDataContext(string url, string dbName)
{
MongoClientSettings settings = MongoClientSettings.FromUrl(
new MongoUrl(url)
);
settings.MaxConnectionIdleTime = TimeSpan.FromMinutes(1);
settings.MaxConnectionPoolSize = Convert.ToInt16(10000);
settings.MinConnectionPoolSize = Convert.ToInt16(1);
var client = new MongoClient(settings);
MongoDatabase = client.GetDatabase(dbName);
CreateCollections(dbName);
}
public IMongoDatabase MongoDatabase { get; }
protected void CreateCollections(string dbName)
{
var tCollection = MongoDatabase.GetCollection<Record>("LedZepplin");
}
# region IDisposable
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
}
}
this.disposed = true;
}
# endregion
}
}
This is what my MongoDB log looks like after executing the code.
2022-07-14T21:31:56.032+0000 I NETWORK [listener] connection accepted from <My IP Address>:60645 #1437728 (21 connections now open)
2022-07-14T21:31:56.039+0000 I NETWORK [conn1437728] received client metadata from <My IP Address>:60645 conn1437728: { application: { name: "MongoDB Compass Community" }, driver: { name: "mongo-csharp-driver", version: "2.16.1.0" }, os: { type: "Windows", name: "Microsoft Windows 10.0.22000", architecture: "x86_32", version: "10.0.22000" }, platform: ".NET Framework 4.8.4515.0" }
2022-07-14T21:31:56.163+0000 I ACCESS [conn1437728] Successfully authenticated as principal UserDataStorage152 on DataStorage152
2022-07-14T21:32:56.312+0000 I NETWORK [listener] connection accepted from <My IP Address>:60652 #1437735 (21 connections now open)
2022-07-14T21:32:56.312+0000 I NETWORK [conn1437735] received client metadata from <My IP Address>:60652 conn1437735: { application: { name: "MongoDB Compass Community" }, driver: { name: "mongo-csharp-driver", version: "2.16.1.0" }, os: { type: "Windows", name: "Microsoft Windows 10.0.22000", architecture: "x86_32", version: "10.0.22000" }, platform: ".NET Framework 4.8.4515.0" }
2022-07-14T21:32:56.452+0000 I ACCESS [conn1437735] Successfully authenticated as principal UserDataStorage152 on DataStorage152
2022-07-14T21:33:56.597+0000 I NETWORK [listener] connection accepted from <My IP Address>:60657 #1437742 (21 connections now open)
2022-07-14T21:33:56.603+0000 I NETWORK [conn1437742] received client metadata from <My IP Address>:60657 conn1437742: { application: { name: "MongoDB Compass Community" }, driver: { name: "mongo-csharp-driver", version: "2.16.1.0" }, os: { type: "Windows", name: "Microsoft Windows 10.0.22000", architecture: "x86_32", version: "10.0.22000" }, platform: ".NET Framework 4.8.4515.0" }
2022-07-14T21:33:56.751+0000 I ACCESS [conn1437742] Successfully authenticated as principal UserDataStorage152 on DataStorage152