Browse Source

Add DBHelper class and route all database calls through it.

Brett Credo 8 years ago
parent
commit
246bb928ec

+ 26 - 29
BulkPrinting/BulkPrinting/BatchForm.cs

34
         {
34
         {
35
             Dictionary<int, BatchEvent> BatchEvents = new Dictionary<int, BatchEvent>();
35
             Dictionary<int, BatchEvent> BatchEvents = new Dictionary<int, BatchEvent>();
36
             string Sql = "Select COUNT(v.BatchId) AS Total, v.BatchId,l.EventType,l.Retry FROM Voucher v LEFT JOIN Logs l on v.Id = l.VoucherId WHERE l.EventType in (@printevent,@exportevent) GROUP BY v.BatchId,l.EventType,l.Retry ORDER BY BatchId";
36
             string Sql = "Select COUNT(v.BatchId) AS Total, v.BatchId,l.EventType,l.Retry FROM Voucher v LEFT JOIN Logs l on v.Id = l.VoucherId WHERE l.EventType in (@printevent,@exportevent) GROUP BY v.BatchId,l.EventType,l.Retry ORDER BY BatchId";
37
-            using (var Command = new SQLiteCommand(Sql, Globals.DBConnection))
37
+            using (var Command = Globals.DB.CreateCommand(Sql,
38
+                new SQLiteParameter("@printevent", VendorEvent.VendorEventType.PrintVoucher),
39
+                new SQLiteParameter("@exportevent", VendorEvent.VendorEventType.ExportVoucher)))
38
             {
40
             {
39
-                Command.Parameters.AddWithValue("@printevent", VendorEvent.VendorEventType.PrintVoucher);
40
-                Command.Parameters.AddWithValue("@exportevent", VendorEvent.VendorEventType.ExportVoucher);
41
                 using (SQLiteDataReader read = Command.ExecuteReader())
41
                 using (SQLiteDataReader read = Command.ExecuteReader())
42
                 {
42
                 {
43
                     while (read.Read())
43
                     while (read.Read())
90
             //dgvBatches.Columns.Add("VoucherCount", "Voucher Count");
90
             //dgvBatches.Columns.Add("VoucherCount", "Voucher Count");
91
 
91
 
92
 
92
 
93
-            using (var Command = new SQLiteCommand(Sql, Globals.DBConnection))
93
+            CultureInfo IVC = CultureInfo.InvariantCulture;
94
+            using (var Command = Globals.DB.CreateCommand(Sql,
95
+                new SQLiteParameter("@startdate", dtpFilterStartDate.Value.Date.ToString("yyyy-MM-dd 00:00:00", IVC)),
96
+                new SQLiteParameter("@enddate", dtpFilterEndDate.Value.Date.ToString("yyyy-MM-dd 23:59:59", IVC))))
94
             {
97
             {
95
-                CultureInfo IVC = CultureInfo.InvariantCulture;
96
-                Command.Parameters.AddWithValue("@startdate", dtpFilterStartDate.Value.Date.ToString("yyyy-MM-dd 00:00:00", IVC));
97
-                Command.Parameters.AddWithValue("@enddate", dtpFilterEndDate.Value.Date.ToString("yyyy-MM-dd 23:59:59", IVC));
98
-
99
                 lblLoading.Hide();
98
                 lblLoading.Hide();
100
                 using (SQLiteDataReader read = Command.ExecuteReader())
99
                 using (SQLiteDataReader read = Command.ExecuteReader())
101
                 {
100
                 {
264
 
263
 
265
             LoadingThread = new Thread(LoadingThreadWorker);
264
             LoadingThread = new Thread(LoadingThreadWorker);
266
             LoadingThread.Start();
265
             LoadingThread.Start();
267
-            Utility.InitialiseUserLimits(Globals.DBConnection);
266
+            Utility.InitialiseUserLimits(Globals.DB);
268
             ReSyncTimer.Enabled = true;
267
             ReSyncTimer.Enabled = true;
269
         }
268
         }
270
 
269
 
271
         private void LoadingThreadWorker()
270
         private void LoadingThreadWorker()
272
         {
271
         {
273
             const int voucherPageSize = 5000;
272
             const int voucherPageSize = 5000;
274
-            var conn = Globals.DBConnection;
275
-            //using (var conn = Utility.OpenDBConnection())
273
+            var db = Globals.DB;
274
+            //using (var db = Utility.OpenDBConnection())
276
             {
275
             {
277
                 Invoke(new Action(() =>
276
                 Invoke(new Action(() =>
278
                 {
277
                 {
279
                     PopulateGrid();
278
                     PopulateGrid();
280
                 }));
279
                 }));
281
 
280
 
282
-                var lastSyncedBatchId = Utility.GetSavedParameterAsInt(conn, "LastSyncedBatchId");
281
+                var lastSyncedBatchId = Utility.GetSavedParameterAsInt(db, "LastSyncedBatchId");
283
 
282
 
284
                 bool skipNewBatchCheck = false;
283
                 bool skipNewBatchCheck = false;
285
                 while (true)
284
                 while (true)
330
                                         foreach (var batch in BatchPage.Items)
329
                                         foreach (var batch in BatchPage.Items)
331
                                         {
330
                                         {
332
                                             refreshGrid = true;
331
                                             refreshGrid = true;
333
-                                            Utility.SaveBatch(conn, batch);
332
+                                            Utility.SaveBatch(db, batch);
334
                                             lastSyncedBatchId = batch.Id;
333
                                             lastSyncedBatchId = batch.Id;
335
-                                            if (!Utility.UpdateSavedParameter(conn, "LastSyncedBatchId", lastSyncedBatchId))
334
+                                            if (!Utility.UpdateSavedParameter(db, "LastSyncedBatchId", lastSyncedBatchId))
336
                                             {
335
                                             {
337
                                                 // Shouldn't happen.
336
                                                 // Shouldn't happen.
338
                                                 throw new Exception("Failed to update LastSyncedBatchId");
337
                                                 throw new Exception("Failed to update LastSyncedBatchId");
363
                         // Continue downloading incomplete batches if any.
362
                         // Continue downloading incomplete batches if any.
364
                         try
363
                         try
365
                         {
364
                         {
366
-                            using (var command = new SQLiteCommand(
367
-                                "SELECT Id FROM Batch WHERE Downloaded=0 ORDER BY Downloaded, Id",
368
-                                conn))
365
+                            using (var command = db.CreateCommand("SELECT Id FROM Batch WHERE Downloaded=0 ORDER BY Downloaded, Id"))
369
                             {
366
                             {
370
                                 using (SQLiteDataReader row = command.ExecuteReader())
367
                                 using (SQLiteDataReader row = command.ExecuteReader())
371
                                 {
368
                                 {
380
                                             if (Utility.RESTRequest(ref batch, String.Format("/api/batches/{0}", batchId)))
377
                                             if (Utility.RESTRequest(ref batch, String.Format("/api/batches/{0}", batchId)))
381
                                             {
378
                                             {
382
                                                 refreshGrid = true;
379
                                                 refreshGrid = true;
383
-                                                Utility.SaveBatch(conn, batch);
380
+                                                Utility.SaveBatch(db, batch);
384
 
381
 
385
                                                 if (batch.ReadyForDownload)
382
                                                 if (batch.ReadyForDownload)
386
                                                 {
383
                                                 {
387
-                                                    long result = (long)Utility.DBExecuteScalar(conn,
384
+                                                    long result = (long)db.ExecuteScalar(
388
                                                         "SELECT COUNT(*) FROM Voucher WHERE BatchId=@BatchId",
385
                                                         "SELECT COUNT(*) FROM Voucher WHERE BatchId=@BatchId",
389
                                                         new SQLiteParameter("@BatchId", batchId));
386
                                                         new SQLiteParameter("@BatchId", batchId));
390
                                                     int voucherCount = (int)result;
387
                                                     int voucherCount = (int)result;
408
 
405
 
409
                                                         Log.Debug("Downloaded vouchers for batch {0} ({1} so far)", batchId, voucherCount);
406
                                                         Log.Debug("Downloaded vouchers for batch {0} ({1} so far)", batchId, voucherCount);
410
 
407
 
411
-                                                        lock (Globals.DBWriteLock)
408
+                                                        lock (db.WriteLock)
412
                                                         {
409
                                                         {
413
-                                                            using (var trans = conn.BeginTransaction())
410
+                                                            using (var trans = db.BeginTransaction())
414
                                                             {
411
                                                             {
415
-                                                                using (var insert = new SQLiteCommand(
412
+                                                                using (var insert = db.CreateCommand(
416
                                                                     "INSERT INTO Voucher (Id, SequenceNumber, ExpiryDate, Serial, EncryptedPIN, BatchId)" +
413
                                                                     "INSERT INTO Voucher (Id, SequenceNumber, ExpiryDate, Serial, EncryptedPIN, BatchId)" +
417
                                                                                  "VALUES (@Id,@SequenceNumber,@ExpiryDate,@Serial,@EncryptedPin,@BatchId)",
414
                                                                                  "VALUES (@Id,@SequenceNumber,@ExpiryDate,@Serial,@EncryptedPin,@BatchId)",
418
-                                                                    conn, trans))
415
+                                                                    trans))
419
                                                                 {
416
                                                                 {
420
                                                                     for (var i = offset; i < voucherPage.Items.Count; i++)
417
                                                                     for (var i = offset; i < voucherPage.Items.Count; i++)
421
                                                                     {
418
                                                                     {
450
                                                     {
447
                                                     {
451
                                                         Log.Debug("Batch {0} complete", batchId);
448
                                                         Log.Debug("Batch {0} complete", batchId);
452
 
449
 
453
-                                                        Utility.DBExecuteNonQuery(conn,
450
+                                                        db.ExecuteNonQuery(
454
                                                             "UPDATE Batch SET Downloaded=1 WHERE Id=@BatchId",
451
                                                             "UPDATE Batch SET Downloaded=1 WHERE Id=@BatchId",
455
                                                             new SQLiteParameter("@BatchId", batchId));
452
                                                             new SQLiteParameter("@BatchId", batchId));
456
                                                     }
453
                                                     }
461
                                                 // Batch will only be null if we got a 404.
458
                                                 // Batch will only be null if we got a 404.
462
                                                 Log.Debug("Removing deleted batch {0}", batchId);
459
                                                 Log.Debug("Removing deleted batch {0}", batchId);
463
 
460
 
464
-                                                Utility.DBExecuteNonQuery(conn,
461
+                                                db.ExecuteNonQuery(
465
                                                     "DELETE FROM Voucher WHERE BatchId=@BatchId",
462
                                                     "DELETE FROM Voucher WHERE BatchId=@BatchId",
466
                                                     new SQLiteParameter("@BatchId", batchId));
463
                                                     new SQLiteParameter("@BatchId", batchId));
467
 
464
 
468
-                                                Utility.DBExecuteNonQuery(conn,
465
+                                                db.ExecuteNonQuery(
469
                                                     "DELETE FROM Batch WHERE Id=@BatchId",
466
                                                     "DELETE FROM Batch WHERE Id=@BatchId",
470
                                                     new SQLiteParameter("@BatchId", batchId));
467
                                                     new SQLiteParameter("@BatchId", batchId));
471
 
468
 
545
             }
542
             }
546
 
543
 
547
             int DeliveredVoucherCount = (int)dgvBatches.SelectedRows[0].Cells[dgvBatches.Columns["DeliveredQuantity"].Index].Value;
544
             int DeliveredVoucherCount = (int)dgvBatches.SelectedRows[0].Cells[dgvBatches.Columns["DeliveredQuantity"].Index].Value;
548
-            int DownloadedVoucherCount = Convert.ToInt32(Utility.DBExecuteScalar(Globals.DBConnection,
545
+            int DownloadedVoucherCount = Convert.ToInt32(Globals.DB.ExecuteScalar(
549
                 "SELECT COUNT(*) FROM Voucher WHERE BatchId=@id",
546
                 "SELECT COUNT(*) FROM Voucher WHERE BatchId=@id",
550
                 new SQLiteParameter("@id", BatchID)));
547
                 new SQLiteParameter("@id", BatchID)));
551
             if (DownloadedVoucherCount < DeliveredVoucherCount) {
548
             if (DownloadedVoucherCount < DeliveredVoucherCount) {
697
                 MessageBox.Show("This batch has been exported previously. Exported batches cannot be printed.", "Cannot print batch", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
694
                 MessageBox.Show("This batch has been exported previously. Exported batches cannot be printed.", "Cannot print batch", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
698
                 return;
695
                 return;
699
             }
696
             }
700
-            int PrintCount = int.Parse(Utility.DBExecuteScalar(Globals.DBConnection,
697
+            int PrintCount = int.Parse(Globals.DB.ExecuteScalar(
701
                 "SELECT COUNT(*) FROM Voucher v LEFT JOIN Logs l ON v.Id = l.VoucherId AND l.EventType = @eventtype WHERE l.VoucherId IS NOT NULL AND v.BatchId=@batchid AND Retry=0",
698
                 "SELECT COUNT(*) FROM Voucher v LEFT JOIN Logs l ON v.Id = l.VoucherId AND l.EventType = @eventtype WHERE l.VoucherId IS NOT NULL AND v.BatchId=@batchid AND Retry=0",
702
                 new SQLiteParameter("@batchid", BatchID),
699
                 new SQLiteParameter("@batchid", BatchID),
703
                 new SQLiteParameter("@eventtype", VendorEvent.VendorEventType.PrintVoucher)).ToString());
700
                 new SQLiteParameter("@eventtype", VendorEvent.VendorEventType.PrintVoucher)).ToString());
708
             }
705
             }
709
 
706
 
710
             int DeliveredVoucherCount = (int)dgvBatches.SelectedRows[0].Cells[dgvBatches.Columns["DeliveredQuantity"].Index].Value;
707
             int DeliveredVoucherCount = (int)dgvBatches.SelectedRows[0].Cells[dgvBatches.Columns["DeliveredQuantity"].Index].Value;
711
-            int DownloadedVoucherCount = Convert.ToInt32(Utility.DBExecuteScalar(Globals.DBConnection,
708
+            int DownloadedVoucherCount = Convert.ToInt32(Globals.DB.ExecuteScalar(
712
                 "SELECT COUNT(*) FROM Voucher WHERE BatchId=@id",
709
                 "SELECT COUNT(*) FROM Voucher WHERE BatchId=@id",
713
                 new SQLiteParameter("@id", BatchID)));
710
                 new SQLiteParameter("@id", BatchID)));
714
             if (DownloadedVoucherCount < DeliveredVoucherCount)
711
             if (DownloadedVoucherCount < DeliveredVoucherCount)

+ 1 - 0
BulkPrinting/BulkPrinting/BulkPrinting.csproj

155
   </ItemGroup>
155
   </ItemGroup>
156
   <ItemGroup>
156
   <ItemGroup>
157
     <Compile Include="Configuration.cs" />
157
     <Compile Include="Configuration.cs" />
158
+    <Compile Include="DBHelper.cs" />
158
     <Compile Include="ExportForm.cs">
159
     <Compile Include="ExportForm.cs">
159
       <SubType>Form</SubType>
160
       <SubType>Form</SubType>
160
     </Compile>
161
     </Compile>

+ 111 - 0
BulkPrinting/BulkPrinting/DBHelper.cs

1
+using System;
2
+using System.Data.SQLite;
3
+
4
+namespace BulkPrinting
5
+{
6
+    public class DBHelper: IDisposable
7
+    {
8
+        private SQLiteConnection _connection;
9
+        private object _writeLock = new object();
10
+        private bool isDisposed = false;
11
+
12
+        public DBHelper(string dataSource, byte[] password)
13
+        {
14
+            _connection = new SQLiteConnection(dataSource);
15
+            _connection.SetPassword(password);
16
+            _connection.Open();
17
+        }
18
+
19
+        public SQLiteTransaction BeginTransaction()
20
+        {
21
+            return _connection.BeginTransaction();
22
+        }
23
+
24
+        public void Close()
25
+        {
26
+            _connection.Close();
27
+        }
28
+
29
+        public SQLiteCommand CreateCommand()
30
+        {
31
+            return new SQLiteCommand(_connection);
32
+        }
33
+
34
+        public SQLiteCommand CreateCommand(SQLiteTransaction transaction, params SQLiteParameter[] parameters)
35
+        {
36
+            var command = new SQLiteCommand();
37
+            command.Transaction = transaction;
38
+            foreach (var parameter in parameters)
39
+            {
40
+                command.Parameters.Add(parameter);
41
+            }
42
+            return command;
43
+        }
44
+
45
+        public SQLiteCommand CreateCommand(string commandText, SQLiteTransaction transaction = null)
46
+        {
47
+            return new SQLiteCommand(commandText, _connection, transaction);
48
+        }
49
+
50
+        public SQLiteCommand CreateCommand(string commandText, params SQLiteParameter[] parameters)
51
+        {
52
+            var command = new SQLiteCommand(commandText, _connection);
53
+            foreach (var parameter in parameters)
54
+            {
55
+                command.Parameters.Add(parameter);
56
+            }
57
+            return command;
58
+        }
59
+
60
+        protected virtual void Dispose(bool disposing)
61
+        {
62
+            if (isDisposed)
63
+                return;
64
+
65
+            if (disposing)
66
+            {
67
+                if (_connection != null)
68
+                {
69
+                    _connection.Dispose();
70
+                    _connection = null;
71
+                }
72
+            }
73
+
74
+            isDisposed = true;
75
+        }
76
+
77
+        public void Dispose()
78
+        {
79
+            Dispose(true);
80
+        }
81
+
82
+        public int ExecuteNonQuery(string commandText, params SQLiteParameter[] parameters)
83
+        {
84
+            lock (_writeLock)
85
+            {
86
+                using (var command = new SQLiteCommand(commandText, _connection))
87
+                {
88
+                    foreach (var parameter in parameters)
89
+                    {
90
+                        command.Parameters.Add(parameter);
91
+                    }
92
+                    return command.ExecuteNonQuery();
93
+                }
94
+            }
95
+        }
96
+
97
+        public object ExecuteScalar(string commandText, params SQLiteParameter[] parameters)
98
+        {
99
+            using (var command = new SQLiteCommand(commandText, _connection))
100
+            {
101
+                foreach (var parameter in parameters)
102
+                {
103
+                    command.Parameters.Add(parameter);
104
+                }
105
+                return command.ExecuteScalar();
106
+            }
107
+        }
108
+
109
+        public object WriteLock { get { return _writeLock; } }
110
+    }
111
+}

+ 4 - 4
BulkPrinting/BulkPrinting/ExportForm.cs

49
                 Sql += " AND b.NetworkName=@networkname";
49
                 Sql += " AND b.NetworkName=@networkname";
50
             }
50
             }
51
             Sql += " GROUP BY b.Id,b.FaceValue,b.ProductDescription,b.DeliveredQuantity";
51
             Sql += " GROUP BY b.Id,b.FaceValue,b.ProductDescription,b.DeliveredQuantity";
52
-            using (var Command = new SQLiteCommand(Sql, Globals.DBConnection))
52
+            using (var Command = Globals.DB.CreateCommand(Sql))
53
             {
53
             {
54
                 if (cmbNetwork.SelectedItem.ToString() != "All")
54
                 if (cmbNetwork.SelectedItem.ToString() != "All")
55
                 {
55
                 {
97
                 lblBatchType.Text = "Previously Exported Batches";
97
                 lblBatchType.Text = "Previously Exported Batches";
98
             }
98
             }
99
             string Sql = "SELECT DISTINCT NetworkName FROM Batch";
99
             string Sql = "SELECT DISTINCT NetworkName FROM Batch";
100
-            using (var Command = new SQLiteCommand(Sql, Globals.DBConnection))
100
+            using (var Command = Globals.DB.CreateCommand(Sql))
101
             {
101
             {
102
                 cmbNetwork.Items.Clear();
102
                 cmbNetwork.Items.Clear();
103
                 cmbNetwork.Items.Add("All");
103
                 cmbNetwork.Items.Add("All");
153
                     List<EventLog> LogEvents = new List<EventLog>();
153
                     List<EventLog> LogEvents = new List<EventLog>();
154
 
154
 
155
                     string Sql = "SELECT v.Id,v.ExpiryDate,v.Serial,v.EncryptedPIN,b.FaceValue,v.BatchId,v.SequenceNumber,b.ProductDescription,COUNT(l.Id) AS Exports FROM Voucher v LEFT JOIN Logs l ON v.Id = l.VoucherId AND l.EventType=@eventtype LEFT JOIN Batch b ON v.BatchId=b.Id WHERE BatchId=@batchid GROUP BY v.Id,v.ExpiryDate,v.Serial,v.EncryptedPIN,b.FaceValue,v.BatchId,v.SequenceNumber,b.ProductDescription";
155
                     string Sql = "SELECT v.Id,v.ExpiryDate,v.Serial,v.EncryptedPIN,b.FaceValue,v.BatchId,v.SequenceNumber,b.ProductDescription,COUNT(l.Id) AS Exports FROM Voucher v LEFT JOIN Logs l ON v.Id = l.VoucherId AND l.EventType=@eventtype LEFT JOIN Batch b ON v.BatchId=b.Id WHERE BatchId=@batchid GROUP BY v.Id,v.ExpiryDate,v.Serial,v.EncryptedPIN,b.FaceValue,v.BatchId,v.SequenceNumber,b.ProductDescription";
156
-                    using (var Command = new SQLiteCommand(Sql, Globals.DBConnection))
156
+                    using (var Command = Globals.DB.CreateCommand(Sql))
157
                     {
157
                     {
158
                         foreach (BatchItem ExportBatch in lstSelectedBatches.Items)
158
                         foreach (BatchItem ExportBatch in lstSelectedBatches.Items)
159
                         {
159
                         {
205
                             }
205
                             }
206
                         }
206
                         }
207
                     }
207
                     }
208
-                    Utility.LogBulkEvents(Globals.DBConnection, LogEvents);
208
+                    Utility.LogBulkEvents(Globals.DB, LogEvents);
209
                 }
209
                 }
210
                 MessageBox.Show("Vouchers Exported");
210
                 MessageBox.Show("Vouchers Exported");
211
                 this.Close();
211
                 this.Close();

+ 2 - 8
BulkPrinting/BulkPrinting/Globals.cs

1
-using System;
2
-using System.Collections.Generic;
3
-using System.Linq;
4
-using System.Text;
5
-using System.Threading.Tasks;
6
-using System.Data.SQLite;
1
+using System.Collections.Generic;
7
 using System.Threading;
2
 using System.Threading;
8
 
3
 
9
 namespace BulkPrinting
4
 namespace BulkPrinting
12
     {
7
     {
13
         public static string MaxDBPath;
8
         public static string MaxDBPath;
14
         public static string MaxDBFilePath;
9
         public static string MaxDBFilePath;
15
-        public static readonly object DBWriteLock = new object();
10
+        public static DBHelper DB;
16
         public static SessionModes SessionMode;
11
         public static SessionModes SessionMode;
17
         public static OKResponse SessionData;
12
         public static OKResponse SessionData;
18
         public static string HDDSerialNumber;
13
         public static string HDDSerialNumber;
22
         public static byte[] SessionVoucherKey;
17
         public static byte[] SessionVoucherKey;
23
         public static byte[] SessionSalt;
18
         public static byte[] SessionSalt;
24
         public static int SessionIterations;
19
         public static int SessionIterations;
25
-        public static SQLiteConnection DBConnection;
26
         public static Printer MaxPrinter;
20
         public static Printer MaxPrinter;
27
         public static List<int> OpenBatches;
21
         public static List<int> OpenBatches;
28
         public static UserLimits UserCurrentUsage;
22
         public static UserLimits UserCurrentUsage;

+ 14 - 16
BulkPrinting/BulkPrinting/Migrations.cs

1
 using System;
1
 using System;
2
-using System.Data.SQLite;
3
-using System.IO;
4
 
2
 
5
 namespace BulkPrinting
3
 namespace BulkPrinting
6
 {
4
 {
7
     class Migrations
5
     class Migrations
8
     {
6
     {
9
-        public static void CheckMigrations(SQLiteConnection conn) {
10
-            var result = Utility.DBExecuteScalar(conn, "SELECT Value FROM Parameters WHERE Key = 'Migration'");
7
+        public static void CheckMigrations(DBHelper db) {
8
+            var result = db.ExecuteScalar("SELECT Value FROM Parameters WHERE Key = 'Migration'");
11
             int startingMigration;
9
             int startingMigration;
12
             if (result == null)
10
             if (result == null)
13
             {
11
             {
23
                 throw new Exception("Database is for a newer version of this application. Please upgrade and try again.");
21
                 throw new Exception("Database is for a newer version of this application. Please upgrade and try again.");
24
             }
22
             }
25
             if (startingMigration < 1) {
23
             if (startingMigration < 1) {
26
-                Migration1(conn);
24
+                Migration1(db);
27
             }
25
             }
28
             if (startingMigration < 2)
26
             if (startingMigration < 2)
29
             {
27
             {
30
-                Migration2(conn);
28
+                Migration2(db);
31
             }
29
             }
32
             //Add further migration executions here - Migration = '1', '2', '3' etc
30
             //Add further migration executions here - Migration = '1', '2', '3' etc
33
 
31
 
34
             return;
32
             return;
35
         }
33
         }
36
 
34
 
37
-        private static bool ApplyMigrationQueries(SQLiteConnection conn, params string[] queries)
35
+        private static bool ApplyMigrationQueries(DBHelper db, params string[] queries)
38
         {
36
         {
39
-            lock (Globals.DBWriteLock)
37
+            lock (db.WriteLock)
40
             {
38
             {
41
-                using (var trans = conn.BeginTransaction())
39
+                using (var trans = db.BeginTransaction())
42
                 {
40
                 {
43
                     foreach (var query in queries)
41
                     foreach (var query in queries)
44
                     {
42
                     {
45
-                        using (var command = new SQLiteCommand(query, conn, trans))
43
+                        using (var command = db.CreateCommand(query, trans))
46
                         {
44
                         {
47
                             command.ExecuteNonQuery();
45
                             command.ExecuteNonQuery();
48
                         }
46
                         }
53
             return true;
51
             return true;
54
         }
52
         }
55
 
53
 
56
-        public static bool InitialVersion(SQLiteConnection conn) {
54
+        public static bool InitialVersion(DBHelper db) {
57
             return ApplyMigrationQueries(
55
             return ApplyMigrationQueries(
58
-                conn,
56
+                db,
59
                 "CREATE TABLE Batch (" +
57
                 "CREATE TABLE Batch (" +
60
                     "Id INT," +
58
                     "Id INT," +
61
                     "OrderDate DATETIME," +
59
                     "OrderDate DATETIME," +
121
             );
119
             );
122
         }
120
         }
123
 
121
 
124
-        public static bool Migration1 (SQLiteConnection conn){
122
+        public static bool Migration1 (DBHelper db){
125
             return ApplyMigrationQueries(
123
             return ApplyMigrationQueries(
126
-                conn,
124
+                db,
127
                 "ALTER TABLE Orders ADD COLUMN InternalReference VARCHAR(32)",
125
                 "ALTER TABLE Orders ADD COLUMN InternalReference VARCHAR(32)",
128
                 "ALTER TABLE Batch ADD COLUMN InternalReference VARCHAR(32)",
126
                 "ALTER TABLE Batch ADD COLUMN InternalReference VARCHAR(32)",
129
                 "INSERT INTO Parameters (Key, Value) VALUES ('Migration','1')"
127
                 "INSERT INTO Parameters (Key, Value) VALUES ('Migration','1')"
130
             );
128
             );
131
         }
129
         }
132
 
130
 
133
-        public static bool Migration2(SQLiteConnection conn)
131
+        public static bool Migration2(DBHelper db)
134
         {
132
         {
135
             return ApplyMigrationQueries(
133
             return ApplyMigrationQueries(
136
-                conn,
134
+                db,
137
                 "ALTER TABLE Batch ADD COLUMN Downloaded BOOLEAN",
135
                 "ALTER TABLE Batch ADD COLUMN Downloaded BOOLEAN",
138
                 "CREATE UNIQUE INDEX Batch_Id ON Batch(Id)",
136
                 "CREATE UNIQUE INDEX Batch_Id ON Batch(Id)",
139
                 "CREATE INDEX Batch_OrderDate ON Batch(OrderDate)",
137
                 "CREATE INDEX Batch_OrderDate ON Batch(OrderDate)",

+ 14 - 14
BulkPrinting/BulkPrinting/OrderForm.cs

109
             DialogResult PlaceOrder = MessageBox.Show(OrderReviewMessage, "Proceed?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
109
             DialogResult PlaceOrder = MessageBox.Show(OrderReviewMessage, "Proceed?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
110
             if (PlaceOrder == DialogResult.Yes) {
110
             if (PlaceOrder == DialogResult.Yes) {
111
                 string InternalReference = Utility.GetNextInternalReference();
111
                 string InternalReference = Utility.GetNextInternalReference();
112
-                Utility.DBExecuteNonQuery(Globals.DBConnection,
112
+                Globals.DB.ExecuteNonQuery(
113
                     "INSERT INTO Orders (UserId,UserName,OrderDate,OrderCost,BalanceAfterOrder,InternalReference) VALUES (@userid,@username,datetime('now'),@ordercost,@balanceafterorder,@internalreference)",
113
                     "INSERT INTO Orders (UserId,UserName,OrderDate,OrderCost,BalanceAfterOrder,InternalReference) VALUES (@userid,@username,datetime('now'),@ordercost,@balanceafterorder,@internalreference)",
114
-                        new SQLiteParameter("@userid", Globals.SessionData.Credentials.Payload.User.Id),
115
-                        new SQLiteParameter("@username", Globals.SessionData.Credentials.Payload.User.FirstName + " " + Globals.SessionData.Credentials.Payload.User.Surname),
116
-                        new SQLiteParameter("@ordercost", TotalCost),
117
-                        new SQLiteParameter("@balanceafterorder", Globals.SessionData.Credentials.Payload.User.Account.Balance - TotalCost),
118
-                        new SQLiteParameter("@internalreference", InternalReference));
114
+                    new SQLiteParameter("@userid", Globals.SessionData.Credentials.Payload.User.Id),
115
+                    new SQLiteParameter("@username", Globals.SessionData.Credentials.Payload.User.FirstName + " " + Globals.SessionData.Credentials.Payload.User.Surname),
116
+                    new SQLiteParameter("@ordercost", TotalCost),
117
+                    new SQLiteParameter("@balanceafterorder", Globals.SessionData.Credentials.Payload.User.Account.Balance - TotalCost),
118
+                    new SQLiteParameter("@internalreference", InternalReference));
119
 
119
 
120
-                int OrderId = int.Parse(Utility.DBExecuteScalar(Globals.DBConnection, "SELECT MAX(Id) FROM Orders").ToString());
120
+                int OrderId = int.Parse(Globals.DB.ExecuteScalar("SELECT MAX(Id) FROM Orders").ToString());
121
 
121
 
122
-                lock (Globals.DBWriteLock)
122
+                lock (Globals.DB.WriteLock)
123
                 {
123
                 {
124
-                    using (var trans = Globals.DBConnection.BeginTransaction())
124
+                    using (var trans = Globals.DB.BeginTransaction())
125
                     {
125
                     {
126
                         var Sql = "INSERT INTO OrderedItems (OrderId,Cost,Quantity,Description,ProductId) VALUES (@orderId,@cost,@quantity,@description,@productid)";
126
                         var Sql = "INSERT INTO OrderedItems (OrderId,Cost,Quantity,Description,ProductId) VALUES (@orderId,@cost,@quantity,@description,@productid)";
127
-                        using (var Command = new SQLiteCommand(Sql, Globals.DBConnection, trans))
127
+                        using (var Command = Globals.DB.CreateCommand(Sql, trans))
128
                         {
128
                         {
129
                             for (int i = 0; i < this.SelectedProducts.Count; i++)
129
                             for (int i = 0; i < this.SelectedProducts.Count; i++)
130
                             {
130
                             {
149
                 ProgressDialog Progress = new ProgressDialog();
149
                 ProgressDialog Progress = new ProgressDialog();
150
                 Progress.Show();
150
                 Progress.Show();
151
                 Thread t = new Thread(() => {
151
                 Thread t = new Thread(() => {
152
-                    var conn = Globals.DBConnection;
153
-                    //using (var conn = Utility.OpenDBConnection())
152
+                    var db = Globals.DB;
153
+                    //using (var db = Utility.OpenDBConnection())
154
                     {
154
                     {
155
                         Progress.UpdateProgressText("Please wait...");
155
                         Progress.UpdateProgressText("Please wait...");
156
                         Progress.UpdateProgressBar(0);
156
                         Progress.UpdateProgressBar(0);
176
                                 continue;
176
                                 continue;
177
                             }
177
                             }
178
                             //TODO: Handle failed order
178
                             //TODO: Handle failed order
179
-                            Utility.SaveBatch(conn, OrderedBatch.Batch);
179
+                            Utility.SaveBatch(db, OrderedBatch.Batch);
180
                             SourceForm.NewBatchAvailable();
180
                             SourceForm.NewBatchAvailable();
181
                             Globals.SessionData.Credentials.Payload.User.Account.Balance = OrderedBatch.RemainingBalance;
181
                             Globals.SessionData.Credentials.Payload.User.Account.Balance = OrderedBatch.RemainingBalance;
182
-                            Utility.AddUserUsage(conn, UserLimits.UserLimitTypes.BulkOrder, OrderedBatch.Batch.Cost);
182
+                            Utility.AddUserUsage(db, UserLimits.UserLimitTypes.BulkOrder, OrderedBatch.Batch.Cost);
183
                             Progress.UpdateProgressBar((int)Math.Round(100 * (((decimal)i + 1) / (decimal)SelectedProducts.Count)));
183
                             Progress.UpdateProgressBar((int)Math.Round(100 * (((decimal)i + 1) / (decimal)SelectedProducts.Count)));
184
                             Thread.Sleep(50);
184
                             Thread.Sleep(50);
185
                         }
185
                         }

+ 8 - 9
BulkPrinting/BulkPrinting/OrderReport.cs

36
             dgvOrderReport.Columns.Add("DeliveredQuantity", "Delivered Quantity");
36
             dgvOrderReport.Columns.Add("DeliveredQuantity", "Delivered Quantity");
37
             string Sql = "Select o.Id,o.InternalReference,o.UserId,o.UserName,o.OrderDate,oi.Description,o.OrderCost,o.BalanceAfterOrder,oi.Cost,b.RequestedQuantity,b.DeliveredQuantity From Orders o LEFT JOIN OrderedItems oi on oi.OrderId = o.Id LEFT JOIN Batch b ON b.InternalReference = o.InternalReference AND b.ProductId = oi.ProductId WHERE o.OrderDate BETWEEN @startdate AND @enddate";
37
             string Sql = "Select o.Id,o.InternalReference,o.UserId,o.UserName,o.OrderDate,oi.Description,o.OrderCost,o.BalanceAfterOrder,oi.Cost,b.RequestedQuantity,b.DeliveredQuantity From Orders o LEFT JOIN OrderedItems oi on oi.OrderId = o.Id LEFT JOIN Batch b ON b.InternalReference = o.InternalReference AND b.ProductId = oi.ProductId WHERE o.OrderDate BETWEEN @startdate AND @enddate";
38
 
38
 
39
-            using (var Command = new SQLiteCommand(Sql, Globals.DBConnection))
39
+            CultureInfo IVC = CultureInfo.InvariantCulture;
40
+            using (var Command = Globals.DB.CreateCommand(Sql,
41
+                new SQLiteParameter("@startdate", dtpStartDate.Value.ToString("yyyy-MM-dd 00:00:00", IVC)),
42
+                new SQLiteParameter("@enddate", dtpEndDate.Value.ToString("yyyy-MM-dd 23:59:59", IVC))))
40
             {
43
             {
41
-                CultureInfo IVC = CultureInfo.InvariantCulture;
42
-                Command.Parameters.AddWithValue("@startdate", dtpStartDate.Value.ToString("yyyy-MM-dd 00:00:00", IVC));
43
-                Command.Parameters.AddWithValue("@enddate", dtpEndDate.Value.ToString("yyyy-MM-dd 23:59:59", IVC));
44
 
44
 
45
                 using (SQLiteDataReader read = Command.ExecuteReader())
45
                 using (SQLiteDataReader read = Command.ExecuteReader())
46
                 {
46
                 {
106
         private void btnPrint_Click(object sender, EventArgs e)
106
         private void btnPrint_Click(object sender, EventArgs e)
107
         {
107
         {
108
             string Sql = "Select o.Id,o.OrderDate,o.InternalReference,o.UserName,o.OrderCost,o.BalanceAfterOrder,oi.Description,oi.Cost,b.RequestedQuantity,b.DeliveredQuantity From Orders o LEFT JOIN OrderedItems oi on oi.OrderId = o.Id LEFT JOIN Batch b ON b.InternalReference = o.InternalReference AND b.ProductId = oi.ProductId WHERE o.OrderDate BETWEEN @startdate AND @enddate ORDER BY o.Id";
108
             string Sql = "Select o.Id,o.OrderDate,o.InternalReference,o.UserName,o.OrderCost,o.BalanceAfterOrder,oi.Description,oi.Cost,b.RequestedQuantity,b.DeliveredQuantity From Orders o LEFT JOIN OrderedItems oi on oi.OrderId = o.Id LEFT JOIN Batch b ON b.InternalReference = o.InternalReference AND b.ProductId = oi.ProductId WHERE o.OrderDate BETWEEN @startdate AND @enddate ORDER BY o.Id";
109
-            using (var Command = new SQLiteCommand(Sql, Globals.DBConnection))
109
+            CultureInfo IVC = CultureInfo.InvariantCulture;
110
+            using (var Command = Globals.DB.CreateCommand(Sql,
111
+                new SQLiteParameter("@startdate", dtpStartDate.Value.ToString("yyyy-MM-dd 00:00:00", IVC)),
112
+                new SQLiteParameter("@enddate", dtpEndDate.Value.ToString("yyyy-MM-dd 23:59:59", IVC))))
110
             {
113
             {
111
-                CultureInfo IVC = CultureInfo.InvariantCulture;
112
-                Command.Parameters.AddWithValue("@startdate", dtpStartDate.Value.ToString("yyyy-MM-dd 00:00:00", IVC));
113
-                Command.Parameters.AddWithValue("@enddate", dtpEndDate.Value.ToString("yyyy-MM-dd 23:59:59", IVC));
114
-
115
                 int CurrentId;
114
                 int CurrentId;
116
                 int LastId = -1;
115
                 int LastId = -1;
117
                 List<OrderList> Orders = new List<OrderList>();
116
                 List<OrderList> Orders = new List<OrderList>();

+ 4 - 4
BulkPrinting/BulkPrinting/PrintAlignmentDialog.cs

97
             }
97
             }
98
             else if (NumVouchers != null)
98
             else if (NumVouchers != null)
99
             {
99
             {
100
-                FirstVoucherSequenceNumber = Convert.ToInt32(Utility.DBExecuteScalar(Globals.DBConnection,
100
+                FirstVoucherSequenceNumber = Convert.ToInt32(Globals.DB.ExecuteScalar(
101
                     "SELECT MIN(v.SequenceNumber) FROM Voucher v " +
101
                     "SELECT MIN(v.SequenceNumber) FROM Voucher v " +
102
                         "LEFT JOIN Logs l ON v.Id = l.VoucherId AND l.EventType = @eventtype " +
102
                         "LEFT JOIN Logs l ON v.Id = l.VoucherId AND l.EventType = @eventtype " +
103
                         "WHERE v.BatchId = @batchid AND l.id IS NULL",
103
                         "WHERE v.BatchId = @batchid AND l.id IS NULL",
117
             this.Enabled = false;
117
             this.Enabled = false;
118
             Thread t = new Thread(() =>
118
             Thread t = new Thread(() =>
119
             {
119
             {
120
-                var conn = Globals.DBConnection;
121
-                //using (var conn = Utility.OpenDBConnection())
120
+                var db = Globals.DB;
121
+                //using (var db = Utility.OpenDBConnection())
122
                 {
122
                 {
123
-                    Utility.PrintVouchers(conn, BatchID, FirstVoucherSequenceNumber, LastVoucherSequenceNumber);
123
+                    Utility.PrintVouchers(db, BatchID, FirstVoucherSequenceNumber, LastVoucherSequenceNumber);
124
                     Globals.OpenBatches.Remove(BatchID);
124
                     Globals.OpenBatches.Remove(BatchID);
125
                     this.Invoke((Action)(() =>
125
                     this.Invoke((Action)(() =>
126
                     {
126
                     {

+ 1 - 1
BulkPrinting/BulkPrinting/PrintForm.cs

77
             }
77
             }
78
 
78
 
79
             VoucherCount = numNumVouchers.Value;
79
             VoucherCount = numNumVouchers.Value;
80
-            decimal TotalVoucherValue = VoucherCount * (decimal)Utility.DBExecuteScalar(Globals.DBConnection,
80
+            decimal TotalVoucherValue = VoucherCount * (decimal)Globals.DB.ExecuteScalar(
81
                 "SELECT FaceValue FROM Batch WHERE Id = @id",
81
                 "SELECT FaceValue FROM Batch WHERE Id = @id",
82
                 new SQLiteParameter("@id", BatchID));
82
                 new SQLiteParameter("@id", BatchID));
83
 
83
 

+ 7 - 6
BulkPrinting/BulkPrinting/ReprintForm.cs

44
             lblFaceValue.Text = FaceValue;
44
             lblFaceValue.Text = FaceValue;
45
             lblVoucherType.Text = VoucherTypeName;
45
             lblVoucherType.Text = VoucherTypeName;
46
             lblNetwork.Text = NetworkName;
46
             lblNetwork.Text = NetworkName;
47
-            using (var Command = new SQLiteCommand("SELECT MIN(v.SequenceNumber), MAX(v.SequenceNumber) FROM Voucher v LEFT JOIN Logs l ON v.Id = l.VoucherId AND l.EventType = @eventtype WHERE l.VoucherId IS NOT NULL AND v.BatchId=@batchid AND Retry=0", Globals.DBConnection))
47
+            using (var Command = Globals.DB.CreateCommand(
48
+                "SELECT MIN(v.SequenceNumber), MAX(v.SequenceNumber) FROM Voucher v LEFT JOIN Logs l ON v.Id = l.VoucherId AND l.EventType = @eventtype WHERE l.VoucherId IS NOT NULL AND v.BatchId=@batchid AND Retry=0",
49
+                new SQLiteParameter("@batchid", BatchID),
50
+                new SQLiteParameter("@eventtype", VendorEvent.VendorEventType.PrintVoucher)))
48
             {
51
             {
49
-                Command.Parameters.AddWithValue("@batchid", BatchID);
50
-                Command.Parameters.AddWithValue("@eventtype", VendorEvent.VendorEventType.PrintVoucher);
51
                 using (SQLiteDataReader read = Command.ExecuteReader())
52
                 using (SQLiteDataReader read = Command.ExecuteReader())
52
                 {
53
                 {
53
                     read.Read();
54
                     read.Read();
100
                 SelectedRangeEnd = (int)numLastSeqNum.Value;
101
                 SelectedRangeEnd = (int)numLastSeqNum.Value;
101
             }
102
             }
102
             else if (rdoSerial.Checked) {
103
             else if (rdoSerial.Checked) {
103
-                int PrintCount = int.Parse(Utility.DBExecuteScalar(Globals.DBConnection,
104
+                int PrintCount = int.Parse(Globals.DB.ExecuteScalar(
104
                     "SELECT Count(*) FROM Logs l left join Voucher v on l.VoucherId=v.id WHERE v.Serial=@serialnum and l.EventType=@eventtype and Retry=0",
105
                     "SELECT Count(*) FROM Logs l left join Voucher v on l.VoucherId=v.id WHERE v.Serial=@serialnum and l.EventType=@eventtype and Retry=0",
105
                     new SQLiteParameter("@serialnum", txtSerialNum.Text),
106
                     new SQLiteParameter("@serialnum", txtSerialNum.Text),
106
                     new SQLiteParameter("@eventtype", VendorEvent.VendorEventType.PrintVoucher)).ToString());
107
                     new SQLiteParameter("@eventtype", VendorEvent.VendorEventType.PrintVoucher)).ToString());
111
             }
112
             }
112
 
113
 
113
             VoucherCount = SelectedRangeEnd - SelectedRangeStart + 1;
114
             VoucherCount = SelectedRangeEnd - SelectedRangeStart + 1;
114
-            decimal VoucherFaceValue = (decimal)Utility.DBExecuteScalar(Globals.DBConnection,
115
+            decimal VoucherFaceValue = (decimal)Globals.DB.ExecuteScalar(
115
                 "SELECT FaceValue FROM Batch WHERE Id=@id",
116
                 "SELECT FaceValue FROM Batch WHERE Id=@id",
116
                 new SQLiteParameter("@id", BatchID));
117
                 new SQLiteParameter("@id", BatchID));
117
 
118
 
118
-            int UnprintedVouchersInRange = int.Parse(Utility.DBExecuteScalar(Globals.DBConnection,
119
+            int UnprintedVouchersInRange = int.Parse(Globals.DB.ExecuteScalar(
119
                 "SELECT COUNT(v.ID) FROM Voucher v LEFT JOIN Logs l ON v.Id=l.VoucherId AND l.EventType=@event WHERE v.BatchId=@batchid AND v.SequenceNumber BETWEEN @startseq AND @endseq AND l.id IS NULL",
120
                 "SELECT COUNT(v.ID) FROM Voucher v LEFT JOIN Logs l ON v.Id=l.VoucherId AND l.EventType=@event WHERE v.BatchId=@batchid AND v.SequenceNumber BETWEEN @startseq AND @endseq AND l.id IS NULL",
120
                 new SQLiteParameter("@event", (int) VendorEvent.VendorEventType.PrintVoucher),
121
                 new SQLiteParameter("@event", (int) VendorEvent.VendorEventType.PrintVoucher),
121
                 new SQLiteParameter("@batchid", BatchID),
122
                 new SQLiteParameter("@batchid", BatchID),

+ 10 - 10
BulkPrinting/BulkPrinting/UserLoginForm.cs

60
                 }
60
                 }
61
                 else
61
                 else
62
                 {
62
                 {
63
-                    Globals.DBConnection = Utility.OpenDBConnection();
63
+                    Globals.DB = Utility.OpenDBConnection();
64
                     //Test login success
64
                     //Test login success
65
                     Globals.SessionMode = SessionModes.Offline;
65
                     Globals.SessionMode = SessionModes.Offline;
66
-                    Globals.SessionData = JsonConvert.DeserializeObject<OKResponse>(Convert.ToString(Utility.DBExecuteScalar(
67
-                        Globals.DBConnection, "SELECT Value FROM SessionData WHERE Key = 'SessionDataJson'")));
66
+                    Globals.SessionData = JsonConvert.DeserializeObject<OKResponse>(Convert.ToString(Globals.DB.ExecuteScalar(
67
+                        "SELECT Value FROM SessionData WHERE Key = 'SessionDataJson'")));
68
                     Globals.SessionVoucherKey = Utility.AesDecryptBytes(Globals.SessionData.Credentials.Payload.EncryptedVoucherKey, userKey);
68
                     Globals.SessionVoucherKey = Utility.AesDecryptBytes(Globals.SessionData.Credentials.Payload.EncryptedVoucherKey, userKey);
69
                     DateTime ServerDate = Globals.SessionData.Credentials.Payload.Date;
69
                     DateTime ServerDate = Globals.SessionData.Credentials.Payload.Date;
70
                     DateTime Today = DateTime.Now;
70
                     DateTime Today = DateTime.Now;
72
                         MessageBox.Show("It looks like this user hasn't performed an online login today or since the application started. You must perform an online login at least once during the day to use the offline feature. To use offline mode, please remember not to close the application after each session.", "Cannot perform offline login", MessageBoxButtons.OK, MessageBoxIcon.Error);
72
                         MessageBox.Show("It looks like this user hasn't performed an online login today or since the application started. You must perform an online login at least once during the day to use the offline feature. To use offline mode, please remember not to close the application after each session.", "Cannot perform offline login", MessageBoxButtons.OK, MessageBoxIcon.Error);
73
                         return;
73
                         return;
74
                     }
74
                     }
75
-                    Utility.LogEvent(Globals.DBConnection, VendorEvent.VendorEventType.OfflineLogin);
75
+                    Utility.LogEvent(Globals.DB, VendorEvent.VendorEventType.OfflineLogin);
76
                     LoginSuccessful = true;
76
                     LoginSuccessful = true;
77
                 }
77
                 }
78
             }
78
             }
113
                                 Directory.CreateDirectory(Globals.MaxDBPath);
113
                                 Directory.CreateDirectory(Globals.MaxDBPath);
114
                             }
114
                             }
115
                             SQLiteConnection.CreateFile(Globals.MaxDBFilePath);
115
                             SQLiteConnection.CreateFile(Globals.MaxDBFilePath);
116
-                            Globals.DBConnection = Utility.OpenDBConnection();
117
-                            Migrations.InitialVersion(Globals.DBConnection);
116
+                            Globals.DB = Utility.OpenDBConnection();
117
+                            Migrations.InitialVersion(Globals.DB);
118
                         }
118
                         }
119
                         else
119
                         else
120
                         {
120
                         {
121
-                            Globals.DBConnection = Utility.OpenDBConnection();
121
+                            Globals.DB = Utility.OpenDBConnection();
122
                         }
122
                         }
123
-                        Migrations.CheckMigrations(Globals.DBConnection);
124
-                        Utility.CheckLogSynchronisation(Globals.DBConnection);
123
+                        Migrations.CheckMigrations(Globals.DB);
124
+                        Utility.CheckLogSynchronisation(Globals.DB);
125
                         Utility.TriggerLogDownload();
125
                         Utility.TriggerLogDownload();
126
                         Utility.TriggerLogUpload();
126
                         Utility.TriggerLogUpload();
127
                     }
127
                     }
146
                 Globals.SessionData.Credentials.Payload.User.OnlineReprintValue = 0;
146
                 Globals.SessionData.Credentials.Payload.User.OnlineReprintValue = 0;
147
                 Globals.SessionData.Credentials.Payload.User.OfflineReprintValue = 0;
147
                 Globals.SessionData.Credentials.Payload.User.OfflineReprintValue = 0;
148
                 */
148
                 */
149
-                Utility.DBExecuteNonQuery(Globals.DBConnection, "DELETE FROM SessionData"); //Destroy stored session data on login - keep in memory until logout
149
+                Globals.DB.ExecuteNonQuery("DELETE FROM SessionData"); //Destroy stored session data on login - keep in memory until logout
150
                 Globals.MaxPrinter = new Printer();
150
                 Globals.MaxPrinter = new Printer();
151
                 this.txtPassword.Text = "";
151
                 this.txtPassword.Text = "";
152
                 this.Hide();
152
                 this.Hide();

+ 89 - 122
BulkPrinting/BulkPrinting/Utility.cs

46
             return result.Length > 15 ? result.Substring(result.Length - 15, 15) : result;
46
             return result.Length > 15 ? result.Substring(result.Length - 15, 15) : result;
47
         }
47
         }
48
 
48
 
49
-        public static SQLiteConnection OpenDBConnection()
49
+        public static DBHelper OpenDBConnection()
50
         {
50
         {
51
-            var conn = new SQLiteConnection(String.Format("Data Source={0};", Globals.MaxDBFilePath));
52
-            conn.SetPassword(Globals.SessionDatabasePassword);
53
-            conn.Open();
54
-            return conn;
55
-        }
56
-
57
-        public static int DBExecuteNonQuery(SQLiteConnection conn, string query, params SQLiteParameter[] queryParams)
58
-        {
59
-            lock (Globals.DBWriteLock)
60
-            {
61
-                using (var command = new SQLiteCommand(query, conn))
62
-                {
63
-                    foreach (var param in queryParams)
64
-                    {
65
-                        command.Parameters.Add(param);
66
-                    }
67
-                    return command.ExecuteNonQuery();
68
-                }
69
-            }
70
-        }
71
-
72
-        public static object DBExecuteScalar(SQLiteConnection conn, string query, params SQLiteParameter[] queryParams)
73
-        {
74
-            using (var command = new SQLiteCommand(query, conn))
75
-            {
76
-                foreach (var param in queryParams)
77
-                {
78
-                    command.Parameters.Add(param);
79
-                }
80
-                return command.ExecuteScalar();
81
-            }
51
+            return new DBHelper(String.Format("Data Source={0};", Globals.MaxDBFilePath), Globals.SessionDatabasePassword);
82
         }
52
         }
83
 
53
 
84
         public static bool Login(LoginData UserLoginData, bool Offline, bool RememberMe) {
54
         public static bool Login(LoginData UserLoginData, bool Offline, bool RememberMe) {
334
             return InternalReferenceRequest.InternalReference;
304
             return InternalReferenceRequest.InternalReference;
335
         }
305
         }
336
 
306
 
337
-        public static void SaveBatch(SQLiteConnection conn, Batch batch)
307
+        public static void SaveBatch(DBHelper db, Batch batch)
338
         {
308
         {
339
-            lock (Globals.DBWriteLock)
309
+            lock (db.WriteLock)
340
             {
310
             {
341
-                using (var trans = conn.BeginTransaction())
311
+                using (var trans = db.BeginTransaction())
342
                 {
312
                 {
343
-                    using (var command = new SQLiteCommand(conn))
313
+                    using (var command = db.CreateCommand(trans))
344
                     {
314
                     {
345
-                        command.Transaction = trans;
346
-
347
                         command.Parameters.AddWithValue("@Id", batch.Id);
315
                         command.Parameters.AddWithValue("@Id", batch.Id);
348
                         command.Parameters.AddWithValue("@OrderDate", batch.OrderDate);
316
                         command.Parameters.AddWithValue("@OrderDate", batch.OrderDate);
349
                         command.Parameters.AddWithValue("@OrderGuid", batch.OrderGuid);
317
                         command.Parameters.AddWithValue("@OrderGuid", batch.OrderGuid);
383
             }
351
             }
384
         }
352
         }
385
 
353
 
386
-        public static string GetSavedParameter(SQLiteConnection conn, string key)
354
+        public static string GetSavedParameter(DBHelper db, string key)
387
         {
355
         {
388
-            return (string)DBExecuteScalar(conn, "SELECT Value FROM Parameters WHERE Key=@Key",
356
+            return (string)db.ExecuteScalar("SELECT Value FROM Parameters WHERE Key=@Key",
389
                 new SQLiteParameter("@Key", key));
357
                 new SQLiteParameter("@Key", key));
390
         }
358
         }
391
 
359
 
392
-        public static int GetSavedParameterAsInt(SQLiteConnection conn, string key)
360
+        public static int GetSavedParameterAsInt(DBHelper db, string key)
393
         {
361
         {
394
-            return Convert.ToInt32(GetSavedParameter(conn, key));
362
+            return Convert.ToInt32(GetSavedParameter(db, key));
395
         }
363
         }
396
 
364
 
397
-        public static bool GetSavedParameterAsBoolean(SQLiteConnection conn, string key)
365
+        public static bool GetSavedParameterAsBoolean(DBHelper db, string key)
398
         {
366
         {
399
-            return Convert.ToBoolean(GetSavedParameter(conn, key));
367
+            return Convert.ToBoolean(GetSavedParameter(db, key));
400
         }
368
         }
401
 
369
 
402
-        public static bool UpdateSavedParameter(SQLiteConnection conn, string key, object value)
370
+        public static bool UpdateSavedParameter(DBHelper db, string key, object value)
403
         {
371
         {
404
-            return DBExecuteNonQuery(conn,
372
+            return db.ExecuteNonQuery(
405
                 "UPDATE Parameters SET Value=@Value WHERE Key=@Key",
373
                 "UPDATE Parameters SET Value=@Value WHERE Key=@Key",
406
                 new SQLiteParameter("@Key", key),
374
                 new SQLiteParameter("@Key", key),
407
                 new SQLiteParameter("@Value", Convert.ToString(value))) > 0;
375
                 new SQLiteParameter("@Value", Convert.ToString(value))) > 0;
408
         }
376
         }
409
 
377
 
410
-        public static void PrintVouchers(SQLiteConnection conn, int BatchId, int StartSeqNo, int EndSeqNo)
378
+        public static void PrintVouchers(DBHelper db, int BatchId, int StartSeqNo, int EndSeqNo)
411
         {
379
         {
412
 
380
 
413
             int VoucherCount = 0;
381
             int VoucherCount = 0;
427
             List<EventLog> LogEvents = new List<EventLog>();
395
             List<EventLog> LogEvents = new List<EventLog>();
428
 
396
 
429
             IList<PrintVoucher> VoucherRow = new List<PrintVoucher>();
397
             IList<PrintVoucher> VoucherRow = new List<PrintVoucher>();
430
-            using (var Command = new SQLiteCommand("SELECT DISTINCT v.Id,v.SequenceNumber,v.Serial,v.EncryptedPIN,v.BatchId,b.ProductDescription,l.VoucherId From Voucher v LEFT JOIN Batch b on v.BatchId = b.Id LEFT JOIN Logs l ON v.Id = l.VoucherId AND l.EventType = @eventtype WHERE v.BatchId=@batch_id AND v.SequenceNumber BETWEEN @seqstartno AND @seqendno ORDER BY v.SequenceNumber", conn))
398
+            using (var Command = db.CreateCommand("SELECT DISTINCT v.Id,v.SequenceNumber,v.Serial,v.EncryptedPIN,v.BatchId,b.ProductDescription,l.VoucherId From Voucher v LEFT JOIN Batch b on v.BatchId = b.Id LEFT JOIN Logs l ON v.Id = l.VoucherId AND l.EventType = @eventtype WHERE v.BatchId=@batch_id AND v.SequenceNumber BETWEEN @seqstartno AND @seqendno ORDER BY v.SequenceNumber",
399
+                new SQLiteParameter("@batch_id", BatchId),
400
+                new SQLiteParameter("@eventtype", VendorEvent.VendorEventType.PrintVoucher),
401
+                new SQLiteParameter("@seqstartno", StartSeqNo),
402
+                new SQLiteParameter("@seqendno", EndSeqNo)))
431
             {
403
             {
432
-                Command.Parameters.AddWithValue("@batch_id", BatchId);
433
-                Command.Parameters.AddWithValue("@eventtype", VendorEvent.VendorEventType.PrintVoucher);
434
-                Command.Parameters.AddWithValue("@seqstartno", StartSeqNo);
435
-                Command.Parameters.AddWithValue("@seqendno", EndSeqNo);
436
-
437
                 using (SQLiteDataReader read = Command.ExecuteReader())
404
                 using (SQLiteDataReader read = Command.ExecuteReader())
438
                 {
405
                 {
439
                     int JobID = Globals.MaxPrinter.Open("Vouchers");
406
                     int JobID = Globals.MaxPrinter.Open("Vouchers");
515
                     Globals.MaxPrinter.Close();
482
                     Globals.MaxPrinter.Close();
516
                 }
483
                 }
517
             }
484
             }
518
-            LogBulkEvents(conn, LogEvents);
485
+            LogBulkEvents(db, LogEvents);
519
         }
486
         }
520
 
487
 
521
         public enum UserPermissions {
488
         public enum UserPermissions {
558
         public static void Logout() {
525
         public static void Logout() {
559
             if (Globals.SessionData != null)
526
             if (Globals.SessionData != null)
560
             {
527
             {
561
-                DBExecuteNonQuery(Globals.DBConnection, "DELETE FROM SessionData"); //Destroy stored session data
528
+                Globals.DB.ExecuteNonQuery("DELETE FROM SessionData"); //Destroy stored session data
562
                 string SessionDataJson = JsonConvert.SerializeObject(Globals.SessionData);
529
                 string SessionDataJson = JsonConvert.SerializeObject(Globals.SessionData);
563
-                DBExecuteNonQuery(Globals.DBConnection,
530
+                Globals.DB.ExecuteNonQuery(
564
                     "INSERT INTO SessionData (Key,Value) VALUES (@key,@value)",
531
                     "INSERT INTO SessionData (Key,Value) VALUES (@key,@value)",
565
                     new SQLiteParameter("@key", "SessionDataJson"),
532
                     new SQLiteParameter("@key", "SessionDataJson"),
566
                     new SQLiteParameter("@value", SessionDataJson));
533
                     new SQLiteParameter("@value", SessionDataJson));
567
-                LogEvent(Globals.DBConnection, VendorEvent.VendorEventType.Logout);
534
+                LogEvent(Globals.DB, VendorEvent.VendorEventType.Logout);
568
 
535
 
569
                 CancelLogUploadWorker();
536
                 CancelLogUploadWorker();
570
                 CancelLogDownloadWorker();
537
                 CancelLogDownloadWorker();
581
                 }
548
                 }
582
 
549
 
583
                 Globals.UploadNewLogs = false;
550
                 Globals.UploadNewLogs = false;
551
+                Globals.LogUploadThreadCancelled = false;
552
+                Globals.LogDownloadThreadCancelled = false;
584
 
553
 
585
-                Globals.DBConnection.Close();
554
+                Globals.DB.Close();
555
+                Globals.DB.Dispose();
556
+                Globals.DB = null;
586
                 Globals.SessionData = null;
557
                 Globals.SessionData = null;
587
                 Globals.SessionDatabasePassword = null;
558
                 Globals.SessionDatabasePassword = null;
588
                 Globals.SessionVoucherKey = null;
559
                 Globals.SessionVoucherKey = null;
603
             return (int)MetaData.LastVendorEventRemoteId;
574
             return (int)MetaData.LastVendorEventRemoteId;
604
         }
575
         }
605
 
576
 
606
-        public static void CheckLogSynchronisation(SQLiteConnection conn)
577
+        public static void CheckLogSynchronisation(DBHelper db)
607
         {
578
         {
608
-            if (!GetSavedParameterAsBoolean(conn, "LoggingInitialised"))
579
+            if (!GetSavedParameterAsBoolean(db, "LoggingInitialised"))
609
             {
580
             {
610
                 var lastSyncedLogId = GetLastSyncedLogID();
581
                 var lastSyncedLogId = GetLastSyncedLogID();
611
 
582
 
612
                 // If we already have logs then there is no need to synchronise.
583
                 // If we already have logs then there is no need to synchronise.
613
                 // NOTE: logs are synchronised in reverse from SyncBackwardsFromLogId downwards
584
                 // NOTE: logs are synchronised in reverse from SyncBackwardsFromLogId downwards
614
-                if ((long)DBExecuteScalar(conn, "SELECT COUNT(*) FROM Logs") == 0)
585
+                if ((long)db.ExecuteScalar("SELECT COUNT(*) FROM Logs") == 0)
615
                 {
586
                 {
616
-                    UpdateSavedParameter(conn, "SyncBackwardsFromLogId", lastSyncedLogId);
587
+                    UpdateSavedParameter(db, "SyncBackwardsFromLogId", lastSyncedLogId);
617
                 }
588
                 }
618
 
589
 
619
                 // If there are logs on the server then ensure that the log autoincrement value is set to the last
590
                 // If there are logs on the server then ensure that the log autoincrement value is set to the last
620
                 // log ID received by the server so new local logs don't clash with existing log entries on the server.
591
                 // log ID received by the server so new local logs don't clash with existing log entries on the server.
621
                 if (lastSyncedLogId != 0)
592
                 if (lastSyncedLogId != 0)
622
                 {
593
                 {
623
-                    lock (Globals.DBWriteLock)
594
+                    lock (db.WriteLock)
624
                     {
595
                     {
625
-                        using (var trans = conn.BeginTransaction())
596
+                        using (var trans = db.BeginTransaction())
626
                         {
597
                         {
627
-                            using (var command = new SQLiteCommand(conn))
598
+                            using (var command = db.CreateCommand(trans, new SQLiteParameter("@Id", lastSyncedLogId)))
628
                             {
599
                             {
629
-                                command.Transaction = trans;
630
-                                command.Parameters.AddWithValue("@Id", lastSyncedLogId);
631
-
632
                                 command.CommandText = "UPDATE sqlite_sequence SET seq=CASE WHEN IFNULL(seq, 0)<@Id THEN @Id ELSE seq END WHERE name='Logs'";
600
                                 command.CommandText = "UPDATE sqlite_sequence SET seq=CASE WHEN IFNULL(seq, 0)<@Id THEN @Id ELSE seq END WHERE name='Logs'";
633
                                 if (command.ExecuteNonQuery() == 0)
601
                                 if (command.ExecuteNonQuery() == 0)
634
                                 {
602
                                 {
641
                     }
609
                     }
642
                 }
610
                 }
643
 
611
 
644
-                UpdateSavedParameter(conn, "LoggingInitialised", true);
612
+                UpdateSavedParameter(db, "LoggingInitialised", true);
645
             }
613
             }
646
         }
614
         }
647
 
615
 
659
             const int vendorEventPageSize = 1000;
627
             const int vendorEventPageSize = 1000;
660
             const int retryInterval = 30000;
628
             const int retryInterval = 30000;
661
 
629
 
662
-            var conn = Globals.DBConnection;
663
-            //using (var conn = OpenDBConnection())
630
+            var db = Globals.DB;
631
+            //using (var db = OpenDBConnection())
664
             {
632
             {
665
                 bool cancelled = false;
633
                 bool cancelled = false;
666
-                int maxRemoteId = GetSavedParameterAsInt(conn, "SyncBackwardsFromLogId");
634
+                int maxRemoteId = GetSavedParameterAsInt(db, "SyncBackwardsFromLogId");
667
                 while (!cancelled && (maxRemoteId > 0))
635
                 while (!cancelled && (maxRemoteId > 0))
668
                 {
636
                 {
669
                     var EventPage = new Page<VendorEvent>();
637
                     var EventPage = new Page<VendorEvent>();
670
                     if (RESTRequest(ref EventPage, String.Format("/api/vendorevents/?maxRemoteId={0}&pageSize={1}", maxRemoteId, vendorEventPageSize)))
638
                     if (RESTRequest(ref EventPage, String.Format("/api/vendorevents/?maxRemoteId={0}&pageSize={1}", maxRemoteId, vendorEventPageSize)))
671
                     {
639
                     {
672
-                        lock (Globals.DBWriteLock)
640
+                        lock (db.WriteLock)
673
                         {
641
                         {
674
-                            using (var trans = conn.BeginTransaction())
642
+                            using (var trans = db.BeginTransaction())
675
                             {
643
                             {
676
-                                using (var insertCommand = new SQLiteCommand(
644
+                                using (var insertCommand = db.CreateCommand(
677
                                     "INSERT INTO Logs (Id,  UserId,  VoucherId,  EventDate,  EventType,  Retry) " +
645
                                     "INSERT INTO Logs (Id,  UserId,  VoucherId,  EventDate,  EventType,  Retry) " +
678
                                               "VALUES (@id, @userid, @voucherid, @eventdate, @eventtype, @retry)",
646
                                               "VALUES (@id, @userid, @voucherid, @eventdate, @eventtype, @retry)",
679
-                                    conn, trans))
680
-                                using (var updateCommand = new SQLiteCommand(
681
-                                    "UPDATE Parameters SET Value=@Value WHERE Key='SyncBackwardsFromLogId'",
682
-                                    conn, trans))
647
+                                    trans))
648
+                                using (var updateCommand = db.CreateCommand(
649
+                                    "UPDATE Parameters SET Value=@Value WHERE Key='SyncBackwardsFromLogId'", trans))
683
                                 {
650
                                 {
684
                                     foreach (VendorEvent Event in EventPage.Items)
651
                                     foreach (VendorEvent Event in EventPage.Items)
685
                                     {
652
                                     {
756
             const int uploadPageSize = 1000;
723
             const int uploadPageSize = 1000;
757
             var retryInterval = 30000;
724
             var retryInterval = 30000;
758
 
725
 
759
-            var conn = Globals.DBConnection;
760
-            //using (var conn = OpenDBConnection())
726
+            var db = Globals.DB;
727
+            //using (var db = OpenDBConnection())
761
             {
728
             {
762
                 var cancelled = false;
729
                 var cancelled = false;
763
                 while (! cancelled)
730
                 while (! cancelled)
765
                     var uploadFailed = false;
732
                     var uploadFailed = false;
766
                     int lastSyncedLogId = GetLastSyncedLogID();
733
                     int lastSyncedLogId = GetLastSyncedLogID();
767
 
734
 
768
-                    var result = DBExecuteScalar(conn, "SELECT MAX(Id) FROM Logs")?.ToString() ?? "0";
735
+                    var result = db.ExecuteScalar("SELECT MAX(Id) FROM Logs")?.ToString() ?? "0";
769
                     if (string.IsNullOrWhiteSpace(result))
736
                     if (string.IsNullOrWhiteSpace(result))
770
                     {
737
                     {
771
                         result = "0";
738
                         result = "0";
776
                     {
743
                     {
777
                         List<RemoteVendorEvent> eventList = new List<RemoteVendorEvent>();
744
                         List<RemoteVendorEvent> eventList = new List<RemoteVendorEvent>();
778
                         int counter = 0;
745
                         int counter = 0;
779
-                        using (var Command = new SQLiteCommand("Select Id,UserId,VoucherId,EventDate,EventType From Logs WHERE Id > @id", conn))
746
+                        using (var Command = db.CreateCommand("Select Id,UserId,VoucherId,EventDate,EventType From Logs WHERE Id > @id",
747
+                            new SQLiteParameter("@id", lastSyncedLogId)))
780
                         {
748
                         {
781
-                            Command.Parameters.AddWithValue("@id", lastSyncedLogId);
782
                             using (SQLiteDataReader read = Command.ExecuteReader())
749
                             using (SQLiteDataReader read = Command.ExecuteReader())
783
                             {
750
                             {
784
                                 while (read.Read())
751
                                 while (read.Read())
818
                                 if (counter > 0)
785
                                 if (counter > 0)
819
                                 {
786
                                 {
820
                                     var response = new RemoteVendorEventResponse();
787
                                     var response = new RemoteVendorEventResponse();
821
-                                    if (! RESTRequest(eventList, ref response, "/api/vendorevents/"))
788
+                                    if (!RESTRequest(eventList, ref response, "/api/vendorevents/"))
822
                                     {
789
                                     {
823
                                         uploadFailed = true;
790
                                         uploadFailed = true;
824
                                     }
791
                                     }
861
             }
828
             }
862
         }
829
         }
863
 
830
 
864
-        public static void LogBulkEvents(SQLiteConnection conn, List<EventLog> EventLogs)
831
+        public static void LogBulkEvents(DBHelper db, List<EventLog> EventLogs)
865
         {
832
         {
866
             string Sql = "INSERT INTO Logs (UserId, VoucherId, EventDate, EventType, Retry) VALUES (@userid, @voucherid, @eventdate, @eventtype, @retry)";
833
             string Sql = "INSERT INTO Logs (UserId, VoucherId, EventDate, EventType, Retry) VALUES (@userid, @voucherid, @eventdate, @eventtype, @retry)";
867
 
834
 
868
-            lock (Globals.DBWriteLock)
835
+            lock (db.WriteLock)
869
             {
836
             {
870
-                using (var trans = conn.BeginTransaction())
837
+                using (var trans = db.BeginTransaction())
871
                 {
838
                 {
872
-                    using (var Command = new SQLiteCommand(Sql, conn, trans))
839
+                    using (var Command = db.CreateCommand(Sql, trans))
873
                     {
840
                     {
874
                         foreach (var EventLog in EventLogs)
841
                         foreach (var EventLog in EventLogs)
875
                         {
842
                         {
892
             }
859
             }
893
         }
860
         }
894
 
861
 
895
-        public static void LogEvent(SQLiteConnection conn, VendorEvent.VendorEventType EventType, int? VoucherId = null, bool Retry = false)
862
+        public static void LogEvent(DBHelper db, VendorEvent.VendorEventType EventType, int? VoucherId = null, bool Retry = false)
896
         {
863
         {
897
-            DBExecuteNonQuery(conn,
864
+            db.ExecuteNonQuery(
898
                 "INSERT INTO Logs (UserId,  VoucherId,  EventDate,  EventType,  Retry) " +
865
                 "INSERT INTO Logs (UserId,  VoucherId,  EventDate,  EventType,  Retry) " +
899
                           "VALUES (@userid, @voucherid, @eventdate, @eventtype, @retry)",
866
                           "VALUES (@userid, @voucherid, @eventdate, @eventtype, @retry)",
900
                 new SQLiteParameter("@userid", Globals.SessionData.Credentials.Payload.User.Id),
867
                 new SQLiteParameter("@userid", Globals.SessionData.Credentials.Payload.User.Id),
908
             }
875
             }
909
         }
876
         }
910
 
877
 
911
-        private static void SaveCurrentUserUsage(SQLiteConnection conn) {
912
-            DBExecuteNonQuery(conn,
878
+        private static void SaveCurrentUserUsage(DBHelper db) {
879
+            db.ExecuteNonQuery(
913
                 "DELETE FROM AccessControlTracking WHERE UserID = @userid",
880
                 "DELETE FROM AccessControlTracking WHERE UserID = @userid",
914
                 new SQLiteParameter("@userid", Globals.SessionData.Credentials.Payload.User.Id));
881
                 new SQLiteParameter("@userid", Globals.SessionData.Credentials.Payload.User.Id));
915
 
882
 
916
-            DBExecuteNonQuery(conn,
883
+            db.ExecuteNonQuery(
917
                 "INSERT INTO AccessControlTracking (UserID, Date, Permission, CurrentUsage) VALUES " +
884
                 "INSERT INTO AccessControlTracking (UserID, Date, Permission, CurrentUsage) VALUES " +
918
                     "(@userid, datetime('now'), 'OfflinePrint', @offlineprintvalue)," +
885
                     "(@userid, datetime('now'), 'OfflinePrint', @offlineprintvalue)," +
919
                     "(@userid, datetime('now'), 'OfflineReprint', @offlinereprintvalue)," +
886
                     "(@userid, datetime('now'), 'OfflineReprint', @offlinereprintvalue)," +
930
                 new SQLiteParameter("@bulkexport", Globals.UserCurrentUsage.BulkExportValue));
897
                 new SQLiteParameter("@bulkexport", Globals.UserCurrentUsage.BulkExportValue));
931
         }
898
         }
932
 
899
 
933
-        public static void AddUserUsage(SQLiteConnection conn, UserLimits.UserLimitTypes UserLimitType, decimal Value) {
900
+        public static void AddUserUsage(DBHelper db, UserLimits.UserLimitTypes UserLimitType, decimal Value) {
934
             DateTime ServerDate = Globals.SessionData.Credentials.Payload.Date;
901
             DateTime ServerDate = Globals.SessionData.Credentials.Payload.Date;
935
             DateTime Today = DateTime.Now;
902
             DateTime Today = DateTime.Now;
936
             if (ServerDate.Date != Today.Date) //prevent system time tampering
903
             if (ServerDate.Date != Today.Date) //prevent system time tampering
961
             }
928
             }
962
 
929
 
963
             //Immediately write to db to avoid cheating
930
             //Immediately write to db to avoid cheating
964
-            SaveCurrentUserUsage(conn);
931
+            SaveCurrentUserUsage(db);
965
         }
932
         }
966
 
933
 
967
         public static Boolean IsValueWithinRemainingUserLimit(UserLimits.UserLimitTypes UserLimitType, decimal Value) {
934
         public static Boolean IsValueWithinRemainingUserLimit(UserLimits.UserLimitTypes UserLimitType, decimal Value) {
1080
             return 0;
1047
             return 0;
1081
         }
1048
         }
1082
 
1049
 
1083
-        private static int GetVoucherPrintCountFromLogs(SQLiteConnection conn, int VoucherId)
1050
+        private static int GetVoucherPrintCountFromLogs(DBHelper db, int VoucherId)
1084
         {
1051
         {
1085
-            return int.Parse(DBExecuteScalar(conn,
1052
+            return int.Parse(db.ExecuteScalar(
1086
                 "SELECT COUNT(*) FROM Logs WHERE VoucherId=@voucherid AND EventType=@eventtype",
1053
                 "SELECT COUNT(*) FROM Logs WHERE VoucherId=@voucherid AND EventType=@eventtype",
1087
                 new SQLiteParameter("@voucherid", VoucherId),
1054
                 new SQLiteParameter("@voucherid", VoucherId),
1088
                 new SQLiteParameter("@eventtype", (int)VendorEvent.VendorEventType.PrintVoucher)).ToString());
1055
                 new SQLiteParameter("@eventtype", (int)VendorEvent.VendorEventType.PrintVoucher)).ToString());
1089
         }
1056
         }
1090
 
1057
 
1091
-        private static DateTime GetVoucherFirstPrintDateFromLogs(SQLiteConnection conn, int VoucherId)
1058
+        private static DateTime GetVoucherFirstPrintDateFromLogs(DBHelper db, int VoucherId)
1092
         {
1059
         {
1093
-            return (DateTime)DBExecuteScalar(conn,
1060
+            return (DateTime)db.ExecuteScalar(
1094
                 "SELECT MIN(EventDate) FROM Logs WHERE VoucherId=@voucherid AND EventType=@eventtype",
1061
                 "SELECT MIN(EventDate) FROM Logs WHERE VoucherId=@voucherid AND EventType=@eventtype",
1095
                 new SQLiteParameter("@voucherid", VoucherId),
1062
                 new SQLiteParameter("@voucherid", VoucherId),
1096
                 new SQLiteParameter("@eventtype", (int)VendorEvent.VendorEventType.PrintVoucher));
1063
                 new SQLiteParameter("@eventtype", (int)VendorEvent.VendorEventType.PrintVoucher));
1097
         }
1064
         }
1098
 
1065
 
1099
-        private static decimal GetVoucherFaceValue(SQLiteConnection conn, int VoucherId)
1066
+        private static decimal GetVoucherFaceValue(DBHelper db, int VoucherId)
1100
         {
1067
         {
1101
-            return (decimal)DBExecuteScalar(conn,
1068
+            return (decimal)db.ExecuteScalar(
1102
                 "SELECT b.FaceValue FROM Voucher v LEFT JOIN Batch b on v.BatchId = b.Id WHERE v.Id=@voucherid",
1069
                 "SELECT b.FaceValue FROM Voucher v LEFT JOIN Batch b on v.BatchId = b.Id WHERE v.Id=@voucherid",
1103
                 new SQLiteParameter("@voucherid", VoucherId));
1070
                 new SQLiteParameter("@voucherid", VoucherId));
1104
         }
1071
         }
1105
 
1072
 
1106
 
1073
 
1107
-        private static UserLimits CalculateUsageFromLogs(SQLiteConnection conn) {
1074
+        private static UserLimits CalculateUsageFromLogs(DBHelper db) {
1108
             UserLimits CalculateUsage = new UserLimits();
1075
             UserLimits CalculateUsage = new UserLimits();
1109
             CalculateUsage.OfflinePrintValue = 0;
1076
             CalculateUsage.OfflinePrintValue = 0;
1110
             CalculateUsage.OfflineReprintValue = 0;
1077
             CalculateUsage.OfflineReprintValue = 0;
1113
             var CurrentDate = DateTime.Today.Date;
1080
             var CurrentDate = DateTime.Today.Date;
1114
             CultureInfo IVC = CultureInfo.InvariantCulture;
1081
             CultureInfo IVC = CultureInfo.InvariantCulture;
1115
             string Sql = "SELECT VoucherId FROM Logs WHERE UserId=@userid AND EventDate BETWEEN @eventdatea AND @eventdateb AND EventType=@eventtype";
1082
             string Sql = "SELECT VoucherId FROM Logs WHERE UserId=@userid AND EventDate BETWEEN @eventdatea AND @eventdateb AND EventType=@eventtype";
1116
-            using (var Command = new SQLiteCommand(Sql, conn))
1083
+            using (var Command = db.CreateCommand(Sql,
1084
+                new SQLiteParameter("@userid", Globals.SessionData.Credentials.Payload.User.Id),
1085
+                new SQLiteParameter("@eventdatea", CurrentDate.ToString("yyyy-MM-dd 00:00:00", IVC)),
1086
+                new SQLiteParameter("@eventdateb", CurrentDate.ToString("yyyy-MM-dd 23:59:59", IVC)),
1087
+                new SQLiteParameter("@eventtype", (int)VendorEvent.VendorEventType.PrintVoucher)))
1117
             {
1088
             {
1118
-                Command.Parameters.AddWithValue("@userid", Globals.SessionData.Credentials.Payload.User.Id);
1119
-                Command.Parameters.AddWithValue("@eventdatea", CurrentDate.ToString("yyyy-MM-dd 00:00:00", IVC));
1120
-                Command.Parameters.AddWithValue("@eventdateb", CurrentDate.ToString("yyyy-MM-dd 23:59:59", IVC));
1121
-                Command.Parameters.AddWithValue("@eventtype", (int)VendorEvent.VendorEventType.PrintVoucher);
1122
                 int VoucherId;
1089
                 int VoucherId;
1123
                 decimal VoucherFaceValue;
1090
                 decimal VoucherFaceValue;
1124
                 using (SQLiteDataReader read = Command.ExecuteReader())
1091
                 using (SQLiteDataReader read = Command.ExecuteReader())
1126
                     while (read.Read())
1093
                     while (read.Read())
1127
                     {
1094
                     {
1128
                         VoucherId = read.GetInt32(0);
1095
                         VoucherId = read.GetInt32(0);
1129
-                        VoucherFaceValue = GetVoucherFaceValue(conn, VoucherId);
1096
+                        VoucherFaceValue = GetVoucherFaceValue(db, VoucherId);
1130
                         //Don't distinguish between online and offline usage for log recalculations
1097
                         //Don't distinguish between online and offline usage for log recalculations
1131
                         CalculateUsage.OfflinePrintValue += VoucherFaceValue;
1098
                         CalculateUsage.OfflinePrintValue += VoucherFaceValue;
1132
                         CalculateUsage.OnlinePrintValue += VoucherFaceValue;
1099
                         CalculateUsage.OnlinePrintValue += VoucherFaceValue;
1133
-                        if (GetVoucherPrintCountFromLogs(conn, VoucherId) > 1)
1100
+                        if (GetVoucherPrintCountFromLogs(db, VoucherId) > 1)
1134
                         { //For reprinted vouchers just assume all prints were reprints - log recalculations should be stricter to prevent cheating
1101
                         { //For reprinted vouchers just assume all prints were reprints - log recalculations should be stricter to prevent cheating
1135
                             CalculateUsage.OfflineReprintValue += VoucherFaceValue;
1102
                             CalculateUsage.OfflineReprintValue += VoucherFaceValue;
1136
                             CalculateUsage.OnlineReprintValue += VoucherFaceValue;
1103
                             CalculateUsage.OnlineReprintValue += VoucherFaceValue;
1141
             return CalculateUsage;
1108
             return CalculateUsage;
1142
         }
1109
         }
1143
 
1110
 
1144
-        public static void InitialiseUserLimits(SQLiteConnection conn)
1111
+        public static void InitialiseUserLimits(DBHelper db)
1145
         {
1112
         {
1146
             Globals.UserCurrentUsage = new UserLimits();
1113
             Globals.UserCurrentUsage = new UserLimits();
1147
             UserLimits CurrentUserLimits = new UserLimits();
1114
             UserLimits CurrentUserLimits = new UserLimits();
1148
 
1115
 
1149
-            int Result = int.Parse(DBExecuteScalar(conn,
1116
+            int Result = int.Parse(db.ExecuteScalar(
1150
                 "SELECT COUNT(*) FROM AccessControlTracking WHERE UserID = @userid",
1117
                 "SELECT COUNT(*) FROM AccessControlTracking WHERE UserID = @userid",
1151
                 new SQLiteParameter("@userid", Globals.SessionData.Credentials.Payload.User.Id)).ToString());
1118
                 new SQLiteParameter("@userid", Globals.SessionData.Credentials.Payload.User.Id)).ToString());
1152
 
1119
 
1153
-            object ResultDate = DBExecuteScalar(conn,
1120
+            object ResultDate = db.ExecuteScalar(
1154
                 "SELECT Date FROM AccessControlTracking WHERE UserID = @userid",
1121
                 "SELECT Date FROM AccessControlTracking WHERE UserID = @userid",
1155
                 new SQLiteParameter("@userid", Globals.SessionData.Credentials.Payload.User.Id));
1122
                 new SQLiteParameter("@userid", Globals.SessionData.Credentials.Payload.User.Id));
1156
 
1123
 
1163
             }
1130
             }
1164
             if (DatePassed)
1131
             if (DatePassed)
1165
             { //Fresh day since last db write or data missing - fetch usage from logs incase of tampering
1132
             { //Fresh day since last db write or data missing - fetch usage from logs incase of tampering
1166
-                Globals.UserCurrentUsage = CalculateUsageFromLogs(conn);
1167
-                SaveCurrentUserUsage(conn); //Immediately write calculated usage to DB
1133
+                Globals.UserCurrentUsage = CalculateUsageFromLogs(db);
1134
+                SaveCurrentUserUsage(db); //Immediately write calculated usage to DB
1168
             }
1135
             }
1169
             else
1136
             else
1170
             {
1137
             {
1171
                 if (Result == 6)
1138
                 if (Result == 6)
1172
                 {
1139
                 {
1173
                     var Sql = "SELECT UserID, Permission, CurrentUsage FROM AccessControlTracking WHERE UserID = @userid";
1140
                     var Sql = "SELECT UserID, Permission, CurrentUsage FROM AccessControlTracking WHERE UserID = @userid";
1174
-                    using (var Command = new SQLiteCommand(Sql, conn))
1141
+                    using (var Command = db.CreateCommand(Sql,
1142
+                        new SQLiteParameter("@userid", Globals.SessionData.Credentials.Payload.User.Id)))
1175
                     {
1143
                     {
1176
-                        Command.Parameters.AddWithValue("@userid", Globals.SessionData.Credentials.Payload.User.Id);
1177
                         using (SQLiteDataReader read = Command.ExecuteReader())
1144
                         using (SQLiteDataReader read = Command.ExecuteReader())
1178
                         {
1145
                         {
1179
                             while (read.Read())
1146
                             while (read.Read())
1205
                 }
1172
                 }
1206
                 else
1173
                 else
1207
                 {
1174
                 {
1208
-                    Globals.UserCurrentUsage = CalculateUsageFromLogs(conn);
1209
-                    SaveCurrentUserUsage(conn); //Immediately write calculated usage to DB
1175
+                    Globals.UserCurrentUsage = CalculateUsageFromLogs(db);
1176
+                    SaveCurrentUserUsage(db); //Immediately write calculated usage to DB
1210
                 }
1177
                 }
1211
             }
1178
             }
1212
         }
1179
         }
1213
 
1180
 
1214
-        public static int GetNumberOfUnprintedVouchersInRange(SQLiteConnection conn, int StartSeqNo, int EndSeqNo, int BatchId) {
1181
+        public static int GetNumberOfUnprintedVouchersInRange(DBHelper db, int StartSeqNo, int EndSeqNo, int BatchId) {
1215
             int UnprintedVouchers = 0;
1182
             int UnprintedVouchers = 0;
1216
             int VoucherId;
1183
             int VoucherId;
1217
             string Sql = "SELECT Id FROM Voucher WHERE SequenceNumber=@sequencenumber AND BatchId=@batchid";
1184
             string Sql = "SELECT Id FROM Voucher WHERE SequenceNumber=@sequencenumber AND BatchId=@batchid";
1218
-            using (var Command = new SQLiteCommand(Sql, conn))
1185
+            using (var Command = db.CreateCommand(Sql))
1219
             {
1186
             {
1220
                 for (int SeqNo = StartSeqNo; SeqNo <= EndSeqNo; SeqNo++)
1187
                 for (int SeqNo = StartSeqNo; SeqNo <= EndSeqNo; SeqNo++)
1221
                 {
1188
                 {
1223
                     Command.Parameters.AddWithValue("@sequencenumber", SeqNo);
1190
                     Command.Parameters.AddWithValue("@sequencenumber", SeqNo);
1224
                     Command.Parameters.AddWithValue("@batchid", BatchId);
1191
                     Command.Parameters.AddWithValue("@batchid", BatchId);
1225
                     VoucherId = int.Parse(Command.ExecuteScalar().ToString());
1192
                     VoucherId = int.Parse(Command.ExecuteScalar().ToString());
1226
-                    int NumPrintedVouchers = GetVoucherPrintCountFromLogs(conn, VoucherId);
1193
+                    int NumPrintedVouchers = GetVoucherPrintCountFromLogs(db, VoucherId);
1227
                     if (NumPrintedVouchers == 0)
1194
                     if (NumPrintedVouchers == 0)
1228
                     {
1195
                     {
1229
                         UnprintedVouchers++;
1196
                         UnprintedVouchers++;

+ 1 - 1
BulkPrinting/BulkPrinting/VoucherForm.cs

52
 
52
 
53
         private void btnSearch_Click(object sender, EventArgs e)
53
         private void btnSearch_Click(object sender, EventArgs e)
54
         {
54
         {
55
-            using (var Command = new SQLiteCommand(Globals.DBConnection))
55
+            using (var Command = Globals.DB.CreateCommand())
56
             {
56
             {
57
                 if (rdoPrintDate.Checked)
57
                 if (rdoPrintDate.Checked)
58
                 {
58
                 {