/// <summary> /// Sends the message to mongo db. /// </summary> /// <returns>The message to mongo db.</returns> /// <param name="entity">Message.</param> private async Task <MongoDBResultState> SendMessageToMongoDB <T>(T entity) where T : Message { MongoDBResultState mongoDBResultState = new MongoDBResultState(); try { MongoClientSettings setting = new MongoClientSettings { Server = new MongoServerAddress("localhost", 27017) }; MongoClient client = new MongoClient(setting); var mongoDbServer = client.GetDatabase(DBName); var collection = mongoDbServer.GetCollection <T>($"{entity.GroupChatName}Messages"); await collection.InsertOneAsync(entity); mongoDBResultState.Result = MongoDBResult.Success; mongoDBResultState.Message = $"Successfully stored message in the {entity.GroupChatName}Messages collection."; } catch (Exception ex) { Console.WriteLine(ex.Message); mongoDBResultState.Message = ex.Message; mongoDBResultState.Result = MongoDBResult.Failure; } return(mongoDBResultState); }
/// <summary> /// Connects to mongo db. /// </summary> /// <returns><c>true</c>, if to mongo db was connected, <c>false</c> otherwise.</returns> /// <param name="entity">Entity.</param> private async Task <MongoDBResultState> ExecuteMongoDBCommand <T>(T entity, MongoDBExecuteCommand mongoDBExecuteCommand) where T : Command { MongoDBResultState mongoDBResultState = new MongoDBResultState(); try { var collection = this.ConnectToMongo(entity); if (collection == null) { return(new MongoDBResultState { Result = MongoDBResult.Failure, Message = $"Unable to create collection {entity.GetType().Name}" }); } switch (mongoDBExecuteCommand) { case MongoDBExecuteCommand.Create: await collection.InsertOneAsync(entity); mongoDBResultState.Message = $"Successfully created {entity.GetType()} in the database."; mongoDBResultState.Result = MongoDBResult.Success; break; case MongoDBExecuteCommand.Update: await collection.ReplaceOneAsync(x => x.ID == entity.ID, entity); mongoDBResultState.Message = $"Successfully updated {entity.GetType()} in the collection."; mongoDBResultState.Result = MongoDBResult.Success; break; case MongoDBExecuteCommand.Delete: await collection.DeleteOneAsync(x => x.ID == entity.ID); mongoDBResultState.Message = $"Successfully deleted {entity.GetType()} in the collection."; mongoDBResultState.Result = MongoDBResult.Success; break; default: mongoDBResultState.Message = $"There was an unknown command executed with ID: {entity.ID}."; mongoDBResultState.Result = MongoDBResult.Failure; break; } } catch (MongoDuplicateKeyException dupEx) { mongoDBResultState.Message = dupEx.Message; mongoDBResultState.Result = MongoDBResult.AlreadyExists; } catch (Exception ex) { mongoDBResultState.Message = ex.Message; mongoDBResultState.Result = MongoDBResult.Failure; } return(mongoDBResultState); }