-
Notifications
You must be signed in to change notification settings - Fork 0
/
DataStore.cs
594 lines (535 loc) · 22.3 KB
/
DataStore.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
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using HtmlElementsDB;
using System.Data.SQLite;
using System.Data;
using HtmlElementsDBEditor.Properties;
using System.IO;
using System.Linq;
namespace HtmlElementsDBEditor
{
/// <summary>
/// Data storage manager for the program.
/// </summary>
internal sealed class DataStore
{
#region MetaDataTable record identifiers
/// <summary>
/// ID of the record in MetaDataTable that stores the database schema version
/// </summary>
const Int32 METADATA_ID_DATABASE_SCHEMA_VERSION = 1;
/// <summary>
/// Identifier for schema version 1
/// </summary>
const Int32 METADATA_ID_DATABASE_SCHEMA_VERSION_1 = 1;
#endregion MetaDataTable record identifiers
#region Constant declarations
/// <summary>
/// Current database schema version ID
/// </summary>
const Int32 DATABASE_SCHEMA_VERSION = 1;
#endregion // Constant declarations
#region SQL statements
/// <summary>
/// SQL command used to create the MetaDataTable table
/// </summary>
private const String SQLite_CreateMetaDataTable = @"
CREATE TABLE MetaDataTable
(
MetaDataId INTEGER NOT NULL PRIMARY KEY,
Code VARCHAR(50),
IntegralValue INTEGER NULL,
StringValue TEXT NULL
)
";
/// <summary>
/// SQL command used to create the AttributeTypes table
/// </summary>
private const String SQLite_CreateAttributeTypes = @"
CREATE TABLE AttributeType
(
AttributeTypeId INTEGER NOT NULL PRIMARY KEY,
Description VARCHAR(80) NOT NULL
)
";
/// <summary>
/// SQL command used to insert the database schema version number into the MetaDataTable table
/// </summary>
private const String SQLite_Insert_MetaData_DatabaseSchemaVersion = @"INSERT INTO MetaDataTable(MetaDataId, Code, IntegralValue) VALUES (1, 'DBSchemaVersion', 1)";
/// <summary>
/// Retrieve all values from the MetaDataTable table
/// </summary>
private const String SQLite_Select_MetaDataTable = @"SELECT MetaDataId, Code, IntegralValue, StringValue FROM MetaDataTable";
#endregion SQL statements
#region Class members
/// <summary>
/// The only instance of the class.
/// </summary>
private static DataStore mInstance;
#endregion Class members
#region Private data members
/// <summary>
/// Flag to indicate that the contents of the document were modified.
/// </summary>
private Boolean mIsModified = false;
/// <summary>
/// Flag to indicate if the document is loaded.
/// </summary>
private Boolean mIsLoaded = false;
/// <summary>
/// Database schema version
/// </summary>
private Int32 mDatabaseSchemaVersion = -1;
/// <summary>
/// Stores HTML element objects.
/// </summary>
private List<DataStorageItem<HtmlElementDTO>> mHtmlElements = new List<DataStorageItem<HtmlElementDTO>>();
/// <summary>
/// Stores attribute data types.
/// </summary>
private List<DataStorageItem<AttributeTypeDTO>> mAttributeDataTypes = new List<DataStorageItem<AttributeTypeDTO>>();
/// <summary>
/// Path to the document file.
/// </summary>
private String mDocumentPath = String.Empty;
#endregion Private data members
#region Construction
/// <summary>
/// Default constructor is hidden.
/// </summary>
private DataStore()
{
}
#endregion Construction
#region Events
/// <summary>
/// This event is raised when a document is opened or closed. The parameter indicates if the document is opened or closed.
/// </summary>
public event EventHandler<Boolean> DocumentOpen;
#endregion Events
#region Public class properties
/// <summary>
/// Gets a reference to the only instance of the class.
/// </summary>
public static DataStore Instance => DataStore.mInstance ?? (DataStore.mInstance = new DataStore());
#endregion // Public class properties
#region Public properties
/// <summary>
/// Gets or sets the flag that indicates that the data was modified.
/// </summary>
public Boolean IsModified
{
get { return this.mIsModified; }
set { this.mIsModified = value; }
}
/// <summary>
/// Gets or sets a flag that indicates if the document is loaded.
/// </summary>
public Boolean IsLoaded
{
get { return this.mIsLoaded; }
private set
{
if (this.mIsLoaded != value)
{
this.mIsLoaded = value;
if (this.DocumentOpen != null)
{
this.DocumentOpen.Invoke(this, true);
}
}
}
}
/// <summary>
/// Gets the path to the document.
/// </summary>
public String FilePath => this.mDocumentPath;
#endregion // Public properties
#region Public methods
/// <summary>
/// Load data.
/// </summary>
/// <param name="dbFilePath">
/// Path to the file where the SQLite database is located.
/// </param>
public void Load(String dbFilePath)
{
// First check if there are changes to save
bool canLoad = false;
if (this.IsModified)
{
if (this.Close())
{
canLoad = true;
}
}
else
{
canLoad = true;
}
// Check if we can proceed with loading the new document.
if (canLoad)
{
LoadDocument(dbFilePath);
this.mDocumentPath = dbFilePath;
}
}
/// <summary>
/// Save data.
/// </summary>
public void Save()
{
if (String.IsNullOrWhiteSpace(this.mDocumentPath))
{
SaveAs();
}
else
{
UpdateDocumentChanges();
}
}
/// <summary>
/// Save data.
/// </summary>
/// <param name="filePath">
/// Path to the output file
/// </param>
public void SaveAs()
{
String newFilePath = this.mDocumentPath;
FrameWindow frameWindow = Application.OpenForms[0] as FrameWindow;
if (frameWindow.GetFilePath(ref newFilePath))
{
SaveNewDocument(newFilePath);
}
}
/// <summary>
/// Create a new document.
/// </summary>
public void CreateNew()
{
if (!this.Close())
{
return;
}
CreateDocument();
}
/// <summary>
/// Close the current document.
/// </summary>
/// <returns>
/// Returns <c>true</c> if the document was closed or <c>false</c> if the user cancelled the close operation.
/// </returns>
public Boolean Close()
{
if (this.IsModified)
{
FrameWindow frameWindow = Application.OpenForms[0] as FrameWindow;
if (frameWindow != null)
{
Boolean result = frameWindow.QueryCanClose();
if (result == true)
{
CloseDocument();
}
return result;
}
}
CloseDocument();
return true;
}
/// <summary>
/// Adds an attribute type to the collection.
/// </summary>
/// <param name="attributeType">
/// New value.
/// </param>
public void AddAttributeDataType(AttributeTypeDTO attributeType)
{
DataStorageItem<AttributeTypeDTO> newRec = new DataStorageItem<AttributeTypeDTO>(new AttributeTypeDTO(GetNextAttributeDataTypeId(), attributeType.Description));
newRec.Added = true;
this.mAttributeDataTypes.Add(newRec);
this.IsModified = true;
}
/// <summary>
/// Remove a record from the attribute data types collection.
/// </summary>
/// <param name="attributeTypeId">
/// ID of the record to delete.
/// </param>
public void DeleteAttributeDataType(uint attributeTypeId)
{
for (int index = 0; index < this.mAttributeDataTypes.Count; ++index)
{
if (this.mAttributeDataTypes[index].Data.AttributeTypeId == attributeTypeId)
{
mAttributeDataTypes[index].Deleted = true;
this.IsModified = true;
return;
}
}
}
/// <summary>
/// Modify an attribute data type record.
/// </summary>
/// <param name="attributeType">
/// New values for the record.
/// </param>
public void ModifyAttributeDataType(AttributeTypeDTO attributeType)
{
for (int index = 0; index < this.mAttributeDataTypes.Count; ++index)
{
if (this.mAttributeDataTypes[index].Data.AttributeTypeId == attributeType.AttributeTypeId)
{
mAttributeDataTypes[index].Data.Description = attributeType.Description;
mAttributeDataTypes[index].Modified = true;
this.IsModified = true;
return;
}
}
}
/// <summary>
/// Creates a copy of the attribute types collection
/// </summary>
/// <returns>
/// Returns a reference to the list of attribute data types
/// </returns>
public IEnumerable<DataStorageItem<AttributeTypeDTO>> CreateAttributeDataTypesCopy()
{
List<DataStorageItem<AttributeTypeDTO>> result = new List<DataStorageItem<AttributeTypeDTO>>();
foreach (DataStorageItem<AttributeTypeDTO> attr in this.mAttributeDataTypes)
{
result.Add(attr.Clone() as DataStorageItem<AttributeTypeDTO>);
}
return result;
}
#endregion // Public methods
#region Private helper methods
/// <summary>
/// Helper method for the <see cref="Close"/> method to close the document.
/// </summary>
private void CloseDocument()
{
mHtmlElements.Clear();
mAttributeDataTypes.Clear();
mDocumentPath = String.Empty;
this.IsModified = false;
this.IsLoaded = false;
}
/// <summary>
/// Helper for the <see cref="Load"/> method.
/// </summary>
/// <param name="dbFilePath"></param>
private void LoadDocument(String dbFilePath)
{
String connectionString = $"Data Source={dbFilePath}; Version=3;";
using (SQLiteConnection dbConnection = new SQLiteConnection(connectionString))
{
dbConnection.Open();
LoadMetaData(dbConnection);
switch (this.mDatabaseSchemaVersion)
{
case METADATA_ID_DATABASE_SCHEMA_VERSION_1:
ReadDatabaseSchemeV1(dbConnection);
this.IsLoaded = true;
break;
default:
throw new DataStoreException(String.Format(Resources.DataStoreException_UnknownDBSchemaVersion, this.mDatabaseSchemaVersion));
}
}
}
/// <summary>
/// Reads data from a schema version 1 type database.
/// </summary>
/// <param name="dbConnection">
/// Open database connection.
/// </param>
private void ReadDatabaseSchemeV1(SQLiteConnection dbConnection)
{
SQLiteDataAccess_v1 dataAccess = new SQLiteDataAccess_v1(dbConnection);
// Read attribute types from the database.
this.mAttributeDataTypes.Clear();
foreach (AttributeTypeDTO attributeType in dataAccess.FetchAttributeTypes())
{
this.mAttributeDataTypes.Add(new DataStorageItem<AttributeTypeDTO>(attributeType));
}
}
/// <summary>
/// Writes data toa a schema version 1 type database.
/// </summary>
/// <param name="dbConnection">
/// Open database connection.
/// </param>
private void StoreDatabaseSchemaV1(SQLiteConnection dbConnection)
{
SQLiteDataAccess_v1 dataAccess = new SQLiteDataAccess_v1(dbConnection);
AddUpdateDeleteSorter<AttributeTypeDTO> sorter = new AddUpdateDeleteSorter<AttributeTypeDTO>(this.mAttributeDataTypes);
dataAccess.AddUpdateDelete_AttributeTypes(sorter.AddedRecords, sorter.ModifiedRecords, sorter.DeletedRecords);
PostSaveUpdateAndRemove(this.mAttributeDataTypes);
}
/// <summary>
/// Helper for <see cref="StoreDatabaseSchemaV1"/> to remove deleted items from a list and clear the tracking flags on the remaining list items.
/// </summary>
/// <typeparam name="T">
/// Type of object stored in the list
/// </typeparam>
/// <param name="list">
/// Reference to the list to update.
/// </param>
private void PostSaveUpdateAndRemove<T>(IList<DataStorageItem<T>> list) where T : class, ICloneable
{
if (list != null)
{
for (int index = list.Count - 1; index >=0; --index)
{
if (list[index].Deleted)
{
list.RemoveAt(index);
}
else
{
list[index].ClearTrackingFlags();
}
}
}
}
/// <summary>
/// Helper for <see cref="LoadDocument"/> to fetch the meta data for the database.
/// </summary>
/// <param name="dbConnection">
/// Database connection object.
/// </param>
private void LoadMetaData(SQLiteConnection dbConnection)
{
using (SQLiteCommand dbCommand = dbConnection.CreateCommand())
{
dbCommand.CommandText = SQLite_Select_MetaDataTable;
dbCommand.CommandType = CommandType.Text;
using (SQLiteDataReader reader = dbCommand.ExecuteReader())
{
int colIndexMetaDataId = reader.GetOrdinal("MetaDataId");
int colIndexCode = reader.GetOrdinal("Code");
int colIndexIntegralValue = reader.GetOrdinal("IntegralValue");
int colIndexStringValue = reader.GetOrdinal("StringValue");
while (reader.Read())
{
switch (reader.GetInt32(colIndexMetaDataId))
{
case METADATA_ID_DATABASE_SCHEMA_VERSION:
this.mDatabaseSchemaVersion = reader.GetInt32(colIndexIntegralValue);
break;
}
}
}
}
}
/// <summary>
/// Helper for the <see cref="CreateNew"/> method.
/// </summary>
private void CreateDocument()
{
this.mDatabaseSchemaVersion = METADATA_ID_DATABASE_SCHEMA_VERSION;
this.IsLoaded = true;
}
/// <summary>
/// Update changes to the existing document.
/// </summary>
private void UpdateDocumentChanges()
{
String connectionString = $"Data Source={this.mDocumentPath}; Version=3;";
using (SQLiteConnection dbConnection = new SQLiteConnection(connectionString))
{
dbConnection.Open();
SQLiteTransaction dbTransaction = dbConnection.BeginTransaction();
try
{
StoreDatabaseSchemaV1(dbConnection);
dbTransaction.Commit();
this.IsModified = false;
}
catch
{
dbTransaction.Rollback();
throw;
}
}
}
/// <summary>
/// Create a new database and store the data.
/// </summary>
/// <param name="documentFilePath">
/// Path to the output file.
/// </param>
private void SaveNewDocument(String documentFilePath)
{
// Delete existing files before creating the new file.
if (File.Exists(documentFilePath))
{
File.Delete(documentFilePath);
}
SQLiteConnection.CreateFile(documentFilePath);
String connectionString = $"Data Source={documentFilePath}; Version=3;";
using (SQLiteConnection dbConnection = new SQLiteConnection(connectionString))
{
dbConnection.Open();
SQLiteTransaction dbTransaction = dbConnection.BeginTransaction();
try
{
// Create the MetaDataTable table
using (SQLiteCommand createCommand = dbConnection.CreateCommand())
{
createCommand.CommandText = SQLite_CreateMetaDataTable;
createCommand.CommandType = CommandType.Text;
createCommand.ExecuteNonQuery();
}
// Create the AttributeTypes table
using (SQLiteCommand createCommand = dbConnection.CreateCommand())
{
createCommand.CommandText = SQLite_CreateAttributeTypes;
createCommand.CommandType = CommandType.Text;
createCommand.ExecuteNonQuery();
}
// Store the database schema version number
using (SQLiteCommand createCommand = dbConnection.CreateCommand())
{
createCommand.CommandText = SQLite_Insert_MetaData_DatabaseSchemaVersion;
createCommand.CommandType = CommandType.Text;
createCommand.ExecuteNonQuery();
}
SQLiteDataAccess_v1 writer = new SQLiteDataAccess_v1(dbConnection);
List<AttributeTypeDTO> attributeTypesList = this.mAttributeDataTypes.ConvertAll<AttributeTypeDTO>(u => u.Data);
writer.AddUpdateDelete_AttributeTypes(attributeTypesList, null, null);
dbTransaction.Commit();
this.IsModified = false;
this.mDocumentPath = documentFilePath;
}
catch
{
dbTransaction.Rollback();
throw;
}
}
}
/// <summary>
/// Get the next attribute data type ID.
/// </summary>
/// <returns>
/// Returns an ID to use for a new record.
/// </returns>
private uint GetNextAttributeDataTypeId()
{
uint nextID = 0;
foreach (var attributeDataType in mAttributeDataTypes)
{
if (attributeDataType.Data.AttributeTypeId > nextID)
{
nextID = attributeDataType.Data.AttributeTypeId;
}
}
return (nextID + 1);
}
#endregion // Private helper methods
} // class DataStore
} // namespace HtmlElementsDBEditor