-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMongoHelper.cs
244 lines (214 loc) · 8.12 KB
/
MongoHelper.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Reflection;
using System.Threading.Tasks;
//Copyright © 2023 Mandala Consulting, LLC MIT License
//Created by Alexander Fields
using MongoDB.Driver;
using MC.Optimization.Logging;
namespace Optimization.Repository
{
/// <summary>
/// Make sure you set the MongoDB Instance before calling the classes in this
/// </summary>
public class MongoHelper : IMongoHelper
{
private static readonly ConcurrentQueue<LogMessage> mongoLogs = new ConcurrentQueue<LogMessage>();
public static event System.EventHandler<LogMessageEventArgs> LogAdded;
public static event System.EventHandler LogCleared;
public IMongoDatabase database { get; set; }
public string dbName { get; set; }
/// <summary>
/// default Constrcutor
/// </summary>
public MongoHelper() { }
~MongoHelper()
{
ClearLogs();
}
/// <summary>
/// Constructor that will get Database
/// </summary>
/// <param name="dbName"></param>
/// <param name="connectionString"></param>
public MongoHelper(string dbName, string connectionString)
{
MongoClient client = new MongoClient(connectionString);
IMongoDatabase db = client.GetDatabase(dbName);
database = db;
}
/// <summary>
/// Helper for connecting to database
/// </summary>
/// <param name="mongoHelper">instance of the mongo helper that will connect</param>
/// <param name="dbName"></param>
/// <param name="username"></param>
/// <param name="password"></param>
/// <param name="cluster"></param>
/// <param name="region">I have no idea if it's actually the region its just an assumption but its different on like all my databases</param>
/// <returns>mongo helper</returns>
public static IMongoHelper MongoHelperConnector(
IMongoHelper mongoHelper,
string dbName,
string username,
string password,
string cluster,
string region
)
{
string connectionString = ConnectionStringBuilder(username, password, cluster, region);
mongoHelper.database = mongoHelper.CreateMongoDbInstance(dbName, connectionString);
try
{
List<string> collections = mongoHelper.TestConnection();
}
catch (System.Exception theseHands)
{
AddLog(LogMessage.Error(theseHands.Message));
}
mongoHelper.dbName = dbName;
return mongoHelper;
}
/// <summary>
/// Connection string builder
/// </summary>
/// <param name="username"></param>
/// <param name="password"></param>
/// <param name="cluster"></param>
/// <param name="region">I have no idea if it's actually the region its just an assumption but its different on like all my databases</param>
/// <returns></returns>
public static string ConnectionStringBuilder(
string username,
string password,
string cluster,
string region
)
{
string encodedPassword = System.Net.WebUtility.UrlEncode(password);
//string connectionString = $"mongodb+srv://{username}:{encodedPassword}@{cluster}.vc4onns.mongodb.net/?retryWrites=true&w=majority";
string connectionString =
$"mongodb+srv://{username}:{encodedPassword}@{cluster}.{region}.mongodb.net/?retryWrites=true&w=majority";
return connectionString;
}
/// <summary>
/// For if already constructed to get Database
/// </summary>
/// <param name="dbName"></param>
/// <param name="connectionString"></param>
/// <returns></returns>
public IMongoDatabase CreateMongoDbInstance(string dbName, string connectionString)
{
MongoClient client = new MongoClient(connectionString);
IMongoDatabase db = client.GetDatabase(dbName);
return db;
}
/// <summary>
/// Tests the connection to the database
/// </summary>
/// <returns>Will return a List of Collection Names if it worked otherwise returns null</returns>
public List<string> TestConnection()
{
try
{
List<string> collectionNames = database.ListCollectionNames().ToList();
return collectionNames;
}
catch (System.Exception e)
{
AddLog(
LogMessage.Error(
"Was unable to properly connect to the database!" + e.ToString()
)
);
return null;
}
}
public async Task<List<T>> GetAllDocumentsAsync<T>(string collectionName)
{
IMongoCollection<T> collection = GetCollection<T>(collectionName);
return await collection.Find(x => true).ToListAsync();
}
public async Task<List<T>> GetFilteredDocumentsAsync<T>(
string collectionName,
FilterDefinition<T> filter
)
{
return await GetCollection<T>(collectionName).Find(filter).ToListAsync();
}
public async Task<ReplaceOneResult> ReplaceDocumentAsync<T>(
string collectionName,
FilterDefinition<T> filter,
T document
)
{
return await GetCollection<T>(collectionName).ReplaceOneAsync(filter, document);
}
public async Task<UpdateResult> UpdateDocumentAsync<T>(
string collectionName,
FilterDefinition<T> filter,
UpdateDefinition<T> document
)
{
return await GetCollection<T>(collectionName).UpdateOneAsync(filter, document);
}
public async Task CreateDocumentAsync<T>(string collectionName, T document)
{
await GetCollection<T>(collectionName).InsertOneAsync(document);
}
public async Task<DeleteResult> DeleteDocumentAsync<T>(string collectionName, FilterDefinition<T> filter)
{
return await GetCollection<T>(collectionName).DeleteOneAsync(filter);
}
private IMongoCollection<T> GetCollection<T>(string collectionName)
{
return database.GetCollection<T>(collectionName);
}
protected static void AddLog(LogMessage logMessage)
{
mongoLogs.Enqueue(logMessage);
LogAdded?.Invoke(null, new LogMessageEventArgs(logMessage));
}
public static void ClearLogs()
{
mongoLogs?.Clear();
LogCleared?.Invoke(null, System.EventArgs.Empty);
}
/// <summary>
/// Get the id for when you don't have an object class
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns>object</returns>
public static object GetIdFromObj<T>(T obj)
{
System.Type typeInfo = typeof(T);
PropertyInfo idProperty = typeInfo.GetProperty("_id");
if (idProperty != null)
{
return idProperty.GetValue(obj, null);
}
return null;
}
/// <summary>
/// Get the id for when you don't have an object class
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns>object</returns>
public static string GetIdFromObjAsString<T>(T obj)
{
System.Type typeInfo = typeof(T);
PropertyInfo idProperty = typeInfo.GetProperty("_id");
if (idProperty != null)
{
string idValue = (string)idProperty.GetValue(obj, null);
return idValue;
}
return null;
}
public static IList<LogMessage> GetLogs()
{
return mongoLogs.ToArray();
}
}
}