-
Notifications
You must be signed in to change notification settings - Fork 64
/
FormatMDB.cs
473 lines (428 loc) · 18.5 KB
/
FormatMDB.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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
// Name: FormatMdb.cs
// Description: Microsoft Access database (.mdb) storage
// Author: Tim Chipman
// Origination: Work performed for BuildingSmart by Constructivity.com LLC.
// Copyright: (c) 2010 BuildingSmart International Ltd.
// License: http://www.buildingsmart-tech.org/legal
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Data.OleDb;
using IfcDoc.Schema;
namespace IfcDoc.Format.MDB
{
public class FormatMDB : IDisposable
{
string m_file;
OleDbConnection m_connection;
Dictionary<string, Type> m_typemap;
Dictionary<long, SEntity> m_instances;
long m_lastOID; // highest inclusive OID
/// <summary>
/// Encapsulates a Microsoft Access database file
/// </summary>
/// <param name="file">Required file path</param>
/// <param name="types">Required map of string identifiers and types</param>
/// <param name="instances">Optional map of instance identifiers and objects (specified if saving)</param>
public FormatMDB(
string file,
Dictionary<string, Type> types,
Dictionary<long, SEntity> instances)
{
this.m_file = file;
this.m_typemap = types;
this.m_instances = instances;
if (m_instances == null)
{
this.m_instances = new Dictionary<long, SEntity>();
}
string connectionstring =
"Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + this.m_file + ";" +
"Jet OLEDB:Engine Type=5;";
// create database if it doesn't exist
bool bNew = false;
if (!System.IO.File.Exists(file))
{
ADOX.CatalogClass cat = new ADOX.CatalogClass();
cat.Create(connectionstring);
bNew = true;
}
this.m_connection = new OleDbConnection(connectionstring);
this.m_connection.Open();
// build schema
if(bNew)
{
foreach (Type t in this.m_typemap.Values)
{
InitType(t);
}
}
}
#region IDisposable Members
public void Dispose()
{
if (this.m_connection != null)
{
this.m_connection.Close();
this.m_connection = null;
}
}
#endregion
public Dictionary<string, Type> Types
{
get
{
return this.m_typemap;
}
}
public Dictionary<long, SEntity> Instances
{
get
{
return this.m_instances;
}
}
private void Execute(string sql)
{
using (OleDbCommand cmd = this.m_connection.CreateCommand())
{
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
}
/// <summary>
/// Creates database table(s) for type
/// </summary>
/// <param name="t"></param>
public void InitType(Type t)
{
StringBuilder sb = new StringBuilder();
sb.Append("CREATE TABLE ");
sb.Append(t.Name);
sb.Append(" (oid INTEGER");
IList<FieldInfo> fields = SEntity.GetFieldsOrdered(t);
foreach (FieldInfo f in fields)
{
if (!f.FieldType.IsGenericType) // don't deal with lists
{
sb.Append(", ");
sb.Append(f.Name);
sb.Append(" ");
if (typeof(SEntity).IsAssignableFrom(f.FieldType))
{
sb.Append(" INTEGER"); // oid
}
else if (f.FieldType.IsEnum)
{
sb.Append(" VARCHAR");
}
else if (typeof(string) == f.FieldType)
{
//if (f.Name.Equals("_Documentation") || f.Name.Equals("_Description") || f.Name.Equals("_Expression"))
if(f.Name.Equals("_Name"))
{
// for name, indexable
sb.Append(" VARCHAR");
}
else
{
// all others unlimited text
sb.Append(" TEXT");
}
}
else if (typeof(bool) == f.FieldType)
{
sb.Append(" BIT");
}
else if (typeof(int) == f.FieldType)
{
sb.Append(" INTEGER");
}
else if (typeof(double) == f.FieldType)
{
sb.Append(" FLOAT");
}
else if (typeof(byte[]) == f.FieldType)
{
sb.Append(" TEXT");
}
else
{
System.Diagnostics.Debug.WriteLine("FormatMDB::InitType() - incompatible field type");
}
}
}
sb.Append(");");
Execute(sb.ToString());
// populate relationships for LISTs
foreach (FieldInfo f in fields)
{
if (f.FieldType.IsGenericType && f.FieldType.GetGenericTypeDefinition() == typeof(List<>))
{
sb = new StringBuilder();
sb.Append("CREATE TABLE ");
sb.Append(t.Name);
sb.Append("_");
sb.Append(f.Name);
sb.Append(" (source INTEGER, sequence INTEGER, target INTEGER);");
Execute(sb.ToString());
}
}
}
public void Register(SEntity entity)
{
this.m_lastOID++;
entity.OID = this.m_lastOID;
this.Instances.Add(this.m_lastOID, entity);
}
/// <summary>
/// Loads all instances from the database
/// </summary>
public void Load()
{
// first pass: load all entities and non-list attributes
foreach (Type t in this.m_typemap.Values)
{
StringBuilder sb = new StringBuilder();
sb.Append("SELECT * FROM ");
sb.Append(t.Name);
IList<FieldInfo> fields = SEntity.GetFieldsOrdered(t);
// load scalar attributes
using (OleDbCommand cmd = this.m_connection.CreateCommand())
{
cmd.CommandText = sb.ToString();
using (OleDbDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
int oid = reader.GetInt32(0);
SEntity entity = null;
if (!this.Instances.TryGetValue(oid, out entity))
{
entity = (SEntity)System.Runtime.Serialization.FormatterServices.GetUninitializedObject(t);
entity.Existing = true;
entity.OID = oid;
this.Instances.Add(entity.OID, entity);
if (entity.OID > m_lastOID)
{
this.m_lastOID = entity.OID;
}
}
int index = 0;
foreach (FieldInfo f in fields)
{
if (!f.FieldType.IsGenericType)
{
// non-list attribute
index++;
object value = reader.GetValue(index);
if (value != null && !(value is DBNull))
{
if (f.FieldType.IsEnum)
{
object eval = Enum.Parse(f.FieldType, value.ToString());
f.SetValue(entity, eval);
}
else if (typeof(SEntity).IsAssignableFrom(f.FieldType))
{
if (value is Int32)
{
int ival = (int)value;
SEntity eval = null;
if (this.Instances.TryGetValue(ival, out eval))
{
f.SetValue(entity, eval);
}
}
}
else if (typeof(byte[]) == f.FieldType)
{
string strval = (string)value;
int len = strval.Length / 2;
Byte[] valuevector = new byte[len];
for (int i = 0; i < len; i++)
{
char hi = strval[i * 2 + 0];
char lo = strval[i * 2 + 1];
byte val = (byte)(
((hi >= 'A' ? +(int)(hi - 'A' + 10) : (int)(hi - '0')) << 4) +
((lo >= 'A' ? +(int)(lo - 'A' + 10) : (int)(lo - '0'))));
valuevector[i] = val;
}
f.SetValue(entity, valuevector);
}
else
{
f.SetValue(entity, value);
}
}
}
}
}
}
}
}
// second pass: load lists (now that all entities are loaded)
foreach (Type t in this.m_typemap.Values)
{
StringBuilder sb = new StringBuilder();
sb.Append("SELECT * FROM ");
sb.Append(t.Name);
sb.Append(";");
IList<FieldInfo> fields = SEntity.GetFieldsOrdered(t);
// load vector attributes
using (OleDbCommand cmd = this.m_connection.CreateCommand())
{
cmd.CommandText = sb.ToString();
using (OleDbDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
long oid = (long)reader.GetInt32(0);
SEntity entity = this.Instances[oid];
foreach (FieldInfo f in fields)
{
if (f.FieldType.IsGenericType)
{
// list
System.Collections.IList list = (System.Collections.IList)f.GetValue(entity);
if (list == null)
{
list = (System.Collections.IList)Activator.CreateInstance(f.FieldType);
f.SetValue(entity, list);
}
using (OleDbCommand cmdList = this.m_connection.CreateCommand())
{
StringBuilder sbl = new StringBuilder();
sbl.Append("SELECT * FROM ");
sbl.Append(t.Name);
sbl.Append("_");
sbl.Append(f.Name);
sbl.Append(" WHERE source=");
sbl.Append(entity.OID.ToString());
sbl.Append(" ORDER BY sequence;");
cmdList.CommandText = sbl.ToString();
using (OleDbDataReader readerList = cmdList.ExecuteReader())
{
while (readerList.Read())
{
long refid = (long)readerList.GetInt32(2);
SEntity target = this.Instances[refid];
list.Add(target);
}
}
}
}
}
}
}
}
}
}
/// <summary>
/// Saves all instances to the database
/// </summary>
public void Save()
{
foreach (SEntity entity in this.Instances.Values)
{
Type t = entity.GetType();
IList<FieldInfo> fields = SEntity.GetFieldsOrdered(t);
if (entity.Existing)
{
//...update attributes...
}
else
{
// create new
StringBuilder sb = new StringBuilder();
sb.Append("INSERT INTO ");
sb.Append(t.Name);
sb.Append("(oid");
foreach (FieldInfo f in fields)
{
if (!f.FieldType.IsGenericType) // don't deal with lists
{
sb.Append(", ");
sb.Append(f.Name);
}
}
sb.Append(") VALUES (");
sb.Append(entity.OID.ToString());
foreach (FieldInfo f in fields)
{
if (!f.FieldType.IsGenericType) // don't deal with lists
{
sb.Append(", ");
object val = f.GetValue(entity);
if (val is SEntity)
{
SEntity entref = (SEntity)val;
sb.Append(entref.OID);
}
else if (val is byte[])
{
byte[] bval = (byte[])val;
sb.Append("'");
sb.Append(BitConverter.ToString(bval));// this.ToString();
sb.Append("'");
}
else if (val != null)
{
string encoded = val.ToString();
if (encoded != null)
{
if (val is string || val is Enum)
{
sb.Append("'");
}
sb.Append(encoded.Replace("'", "''")); // escape single quotes - note: does not handle other unicode quotes
if (val is string || val is Enum)
{
sb.Append("'");
}
}
else
{
sb.Append("NULL");
}
}
else
{
sb.Append("NULL");
}
}
}
sb.Append(");");
Execute(sb.ToString());
entity.Existing = true;
}
// lists
foreach (FieldInfo f in fields)
{
if (f.FieldType.IsGenericType)
{
string tablename = t.Name + "_" + f.Name;
// clear existing
Execute("DELETE FROM " + tablename + " WHERE source=" + entity.OID.ToString() + ";");
System.Collections.IList list = (System.Collections.IList)f.GetValue(entity);
if (list != null)
{
for (int i = 0; i < list.Count; i++)
{
SEntity target = (SEntity)list[i];
Execute("INSERT INTO " + tablename +
" (source, sequence, target) VALUES (" +
entity.OID.ToString() + ", " +
i.ToString() + ", " +
target.OID.ToString() + ");");
}
}
}
}
}
}
}
}