-
Notifications
You must be signed in to change notification settings - Fork 0
/
DATFramework.cs
719 lines (656 loc) · 23.7 KB
/
DATFramework.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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
using OpenDBF.DAT.Generic;
using OpenDBF.DAT.Model;
using OpenDBF.Shared.Generic;
using OpenDBF.Shared.Interface;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Threading;
namespace OpenDBF.DAT
{
/// <summary>
/// Database framework based on object to byte array serialization.
/// </summary>
public class DATFramework : IDatabaseFramework
{
#region Private fields
/// <summary>
/// An active instance of the database.
/// </summary>
private DATDatatable database;
/// <summary>
/// Object used for cross-thread protection.
/// </summary>
private static readonly object lockObject = new object();
/// <summary>
/// Mutex to protect file access from multiple processes.
/// </summary>
protected static Mutex mutex = null;
#endregion
#region Public properties
/// <summary>
/// Returns the current filename of the database with extension.
/// </summary>
public string CurrentFileNameWithExtension => CurrentFileName + ".dat";
/// <summary>
/// Returns the current filename of the database.
/// </summary>
public string CurrentFileName { get; protected set; }
/// <summary>
/// Returns the current workspace of the database.
/// </summary>
public string CurrentWorkspace { get; protected set; }
#endregion
public DATFramework()
{
//Xamarin does not currently support mutexes for some mobile platforms.
//When a new Mutex instance is created by Xamarin.Forms, a NotSupportedException/NotImplementedException is thrown.
//The following code handles this exception. The mutex will be ignored because it is null.
try
{
database = DATDatatable.Generate();
mutex = new Mutex(false, "OpenDBF.DATMutex");
}
catch (Exception ex)
{
if (ex is NotSupportedException || ex is NotImplementedException)
{
Console.WriteLine("Cross-process disabled.");
}
}
}
#region Private methods
/// <summary>
/// Gets a the next available ID in a collection of collectables.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="startID"></param>
/// <returns></returns>
private uint GetNextID<T>(uint startID = 0) where T : ICollectableObject
{
//Gets all elements in the collection
var _collection = database.GetCollection<T>();
if (_collection != null && _collection.Any())
{
//Gets a list of used IDs
IEnumerable<int> idList = _collection.Select(x => (int)x.EID);
return (uint)Enumerable.Range((int)startID, Int32.MaxValue).Except(idList).First();
}
return startID;
}
/// <summary>
/// Gets the next non repeated GUID in a collection of collectables.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
private string GetNextGUID<T>() where T : IIdentifiableObject
{
string newGUID = Guid.NewGuid().ToString().ToUpper();
//Gets all elements in the collection
var _collection = database.Collections.FirstOrDefault(x => x is IEnumerable<T>);
if (_collection is null || !(_collection as IEnumerable<T>).Any())
{
return newGUID;
}
else
{
if ((_collection as IEnumerable<T>).Any(collectableObject => collectableObject.GUID == newGUID))
{
return GetNextGUID<T>();
}
else
{
return newGUID;
}
}
}
#endregion
#region Public methods
/// <summary>
/// Clears the current database framework.
/// </summary>
public void Dispose()
{
lock (lockObject)
{
try
{
try
{
if(mutex != null)
{
mutex.WaitOne();
}
//Reset datatable
database = DATDatatable.Generate();
//Clears internal data
CurrentWorkspace = string.Empty;
CurrentFileName = string.Empty;
}
catch
{
throw;
}
finally
{
if(mutex != null)
{
mutex.ReleaseMutex();
}
}
}
catch
{
throw;
}
finally
{
}
}
}
/// <summary>
/// Saves a selection of items in its respective database.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="items"></param>
public void Commit()
{
lock (lockObject)
{
try
{
try
{
if(mutex != null)
{
mutex.WaitOne();
}
if (database != null)
{
var _dat = database.Serialize();
if (_dat != null)
{
if (!Directory.Exists(CurrentWorkspace))
{
Directory.CreateDirectory(CurrentWorkspace);
}
var fullFilePath = Path.Combine(CurrentWorkspace, CurrentFileNameWithExtension);
File.WriteAllBytes(fullFilePath, _dat);
}
}
}
catch
{
throw;
}
finally
{
if(mutex != null)
{
mutex.ReleaseMutex();
}
}
}
catch
{
throw;
}
finally
{
}
}
}
/// <summary>
/// Deletes a table of items from the current datatable.
/// </summary>
/// <typeparam name="T">An ICollectableObject</typeparam>
/// <returns>Items deleted (true) or not (false)</returns>
public bool DropTable<T>() where T : ICollectableObject
{
bool rc = false;
lock (lockObject)
{
try
{
try
{
if(mutex != null)
{
mutex.WaitOne();
}
if (database != null)
{
rc = database.Collections.RemoveAll(lst => lst.Any(x => x is T)) != 0;
}
}
catch
{
throw;
}
finally
{
if(mutex != null)
{
mutex.ReleaseMutex();
}
}
}
catch
{
throw;
}
finally
{
}
}
return rc;
}
/// <summary>
/// Exports a group of database files to a single zipped file.
/// </summary>
/// <param name="pathToSave">A folder where the database file will be created.</param>
/// <param name="filename">A name for the database file.</param>
/// <param name="fileExtension">An extension for the file.</param>
public void Pack(string pathToSave, string filename, string fileExtension = ".db")
{
//Checks if the path to save ends with a slash and if not, adds it.
if (!pathToSave.Last().Equals('\\'))
{
pathToSave += '\\';
}
lock (lockObject)
{
try
{
try
{
if (mutex != null)
{
mutex.WaitOne();
}
//Make sure the specified directory exists, else creates it
if (!Directory.Exists(pathToSave))
{
Directory.CreateDirectory(pathToSave);
}
//1. Create temp folder with the database files
string tempFolder = Path.Combine(pathToSave, Guid.NewGuid().ToString().ToUpper());
if (!Directory.Exists(Path.Combine(tempFolder)))
{
Directory.CreateDirectory(tempFolder);
}
//2. Copy database file to the temp folder
//Will copy all files matching a database class name
var filesWithDBName = Directory.GetFiles(CurrentWorkspace, CurrentFileName + ".*", SearchOption.TopDirectoryOnly);
if (!filesWithDBName.Any())
{
Commit();
filesWithDBName = Directory.GetFiles(CurrentWorkspace, CurrentFileName + ".*", SearchOption.TopDirectoryOnly);
if (!filesWithDBName.Any())
{
return;
}
}
//Copy files to temp folder
foreach(var f in filesWithDBName)
{
File.Copy(f, Path.Combine(tempFolder, System.IO.Path.GetFileName(f)), true);
}
//3. Archive this temp folder to the database file
string fullFilePath = Path.Combine(pathToSave, filename + fileExtension);
if (File.Exists(fullFilePath))
{
//If the file already exists, delete and recreate
File.Delete(fullFilePath);
}
ZipFile.CreateFromDirectory(tempFolder, fullFilePath, CompressionLevel.Optimal, false);
//4. Delete temp folder
Directory.Delete(tempFolder, true);
}
catch
{
//The exception is caught after the mutex is release.
throw;
}
finally
{
if (mutex != null)
{
mutex.ReleaseMutex();
}
}
}
catch
{
//Exception is caught here and sent to the caller.
throw;
}
finally
{
}
}
}
/// <summary>
/// Gets a selection of items that inherit from ICollectable object from their database collection.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="predicate"></param>
/// <returns></returns>
public IEnumerable<T> Get<T>(Func<T, bool> predicate = null) where T : ICollectableObject
{
IEnumerable<T> output = null;
lock (lockObject)
{
try
{
try
{
if(mutex != null)
{
mutex.WaitOne();
}
if (database != null)
{
output = database.GetCollection(predicate);
}
}
catch
{
throw;
}
finally
{
if(mutex != null)
{
mutex.ReleaseMutex();
}
}
}
catch
{
throw;
}
finally
{
}
}
return output;
}
/// <summary>
/// Imports a zipped database file.
/// </summary>
/// <param name="fileToImport"></param>
/// <param name="exportPath"></param>
public void Unpack(string fileToImport, string exportPath)
{
//This stores the path where the file should be unzipped to,
//including any subfolders that the file was originally in.
string fileUnzipFullPath = string.Empty;
//This is the full name of the destination file including
//the path
string fileUnzipFullName = string.Empty;
lock (lockObject)
{
try
{
try
{
if (mutex != null)
{
mutex.WaitOne();
}
//Opens the zip file up to be read
using (ZipArchive archive = ZipFile.OpenRead(fileToImport))
{
//Loops through each file in the zip file
foreach (ZipArchiveEntry file in archive.Entries)
{
//Identifies the destination file name and path
fileUnzipFullName = Path.Combine(exportPath, file.FullName);
//Extracts the files to the output folder in a safer manner
if (File.Exists(fileUnzipFullName))
{
File.Delete(fileUnzipFullName);
}
//Calculates what the new full path for the unzipped file should be
fileUnzipFullPath = Path.GetDirectoryName(fileUnzipFullName);
//Creates the directory (if it doesn't exist) for the new path
Directory.CreateDirectory(fileUnzipFullPath);
//Extracts the file to (potentially new) path
file.ExtractToFile(fileUnzipFullName);
}
}
}
catch
{
throw;
}
finally
{
if (mutex != null)
{
mutex.ReleaseMutex();
}
}
}
catch
{
throw;
}
finally
{
}
}
}
/// <summary>
/// Inserts a collection of items in the active database.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="items"></param>
public void Insert<T>(IEnumerable<T> items) where T : ICollectableObject
{
Insert(items.ToArray());
}
/// <summary>
/// Inserts one of more items in the active database.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="items"></param>
public void Insert<T>(params T[] items) where T : ICollectableObject
{
lock (lockObject)
{
try
{
try
{
if(mutex != null)
{
mutex.WaitOne();
}
if (items is null || !items.Any())
{
throw new NullReferenceException("No items to insert.");
}
foreach (var item in items)
{
item.EID = GetNextID<T>();
item.GUID = GetNextGUID<T>();
database.Add(item);
}
}
catch
{
throw;
}
finally
{
if(mutex != null)
{
mutex.ReleaseMutex();
}
}
}
catch
{
throw;
}
finally
{
}
}
}
/// <summary>
/// Removes a selection of items that inherit from ICollectable object from their database collection.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="items"></param>
public void Remove<T>(IEnumerable<T> items) where T : ICollectableObject
{
Remove(items.ToArray());
}
/// <summary>
/// Removes a selection of items that inherit from ICollectable object from their database collection.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="items"></param>
public void Remove<T>(params T[] items) where T : ICollectableObject
{
lock (lockObject)
{
try
{
try
{
if(mutex != null)
{
mutex.WaitOne();
}
if (items is null || !items.Any())
{
throw new NullReferenceException("No items to remove.");
}
foreach (var item in items)
{
database.Remove(item);
}
}
catch
{
throw;
}
finally
{
if(mutex != null)
{
mutex.ReleaseMutex();
}
}
}
catch
{
throw;
}
finally
{
}
}
}
/// <summary>
/// Sets the workspace of this class. Type parameters must all inherit from IDatabase.
/// </summary>
/// <param name="workspace"></param>
/// <param name="databaseTypes"></param>
public void SetWorkspace(string workspace, string databaseName = null)
{
lock (lockObject)
{
try
{
try
{
if(mutex != null)
{
mutex.WaitOne();
}
//Checks parameters
//---------------------------------------------------------------------------
if (string.IsNullOrEmpty(workspace))
{
throw new Exception("Cannot have a null workspace.");
}
//---------------------------------------------------------------------------
//Checks if the workspace path ends with a slash and if not, adds it.
if (!workspace.Last().Equals('\\'))
{
workspace += '\\';
}
//Saves the database tyoes and the workspace in the current instance.
CurrentFileName = string.IsNullOrEmpty(databaseName) ? StringUtils.RandomString(8) : Path.GetFileNameWithoutExtension(databaseName);
CurrentWorkspace = workspace;
var fullFilePath = Path.Combine(CurrentWorkspace, CurrentFileNameWithExtension);
if (File.Exists(fullFilePath))
{
var _dat = File.ReadAllBytes(fullFilePath);
database = _dat.Deserialize<DATDatatable>();
}
else
{
//Create random instance of the database
database = DATDatatable.Generate();
if (database != null)
{
//OpenDBF.DAT.Generic.ExtensionMethods.Serialize(datatable);
var _dat = database.Serialize();
if (_dat != null)
{
if (!Directory.Exists(CurrentWorkspace))
{
Directory.CreateDirectory(CurrentWorkspace);
}
File.WriteAllBytes(fullFilePath, _dat);
}
}
}
//Creates the workspace folder if it does not exist.
if (!Directory.Exists(workspace))
{
Directory.CreateDirectory(workspace);
}
}
catch
{
throw;
}
finally
{
if(mutex != null)
{
mutex.ReleaseMutex();
}
}
}
catch
{
throw;
}
finally
{
}
}
}
/// <summary>
/// Updates a selection of items in its respective database.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="items"></param>
public void Update<T>(IEnumerable<T> items) where T : ICollectableObject
{
Remove(items);
Insert(items);
}
#endregion
}
}