Procházet zdrojové kódy

Add DBHelper class and route all database calls through it.

Brett Credo před 8 roky
rodič
revize
246bb928ec

+ 26 - 29
BulkPrinting/BulkPrinting/BatchForm.cs

@@ -34,10 +34,10 @@ namespace BulkPrinting
34 34
         {
35 35
             Dictionary<int, BatchEvent> BatchEvents = new Dictionary<int, BatchEvent>();
36 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 41
                 using (SQLiteDataReader read = Command.ExecuteReader())
42 42
                 {
43 43
                     while (read.Read())
@@ -90,12 +90,11 @@ namespace BulkPrinting
90 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 98
                 lblLoading.Hide();
100 99
                 using (SQLiteDataReader read = Command.ExecuteReader())
101 100
                 {
@@ -264,22 +263,22 @@ namespace BulkPrinting
264 263
 
265 264
             LoadingThread = new Thread(LoadingThreadWorker);
266 265
             LoadingThread.Start();
267
-            Utility.InitialiseUserLimits(Globals.DBConnection);
266
+            Utility.InitialiseUserLimits(Globals.DB);
268 267
             ReSyncTimer.Enabled = true;
269 268
         }
270 269
 
271 270
         private void LoadingThreadWorker()
272 271
         {
273 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 276
                 Invoke(new Action(() =>
278 277
                 {
279 278
                     PopulateGrid();
280 279
                 }));
281 280
 
282
-                var lastSyncedBatchId = Utility.GetSavedParameterAsInt(conn, "LastSyncedBatchId");
281
+                var lastSyncedBatchId = Utility.GetSavedParameterAsInt(db, "LastSyncedBatchId");
283 282
 
284 283
                 bool skipNewBatchCheck = false;
285 284
                 while (true)
@@ -330,9 +329,9 @@ namespace BulkPrinting
330 329
                                         foreach (var batch in BatchPage.Items)
331 330
                                         {
332 331
                                             refreshGrid = true;
333
-                                            Utility.SaveBatch(conn, batch);
332
+                                            Utility.SaveBatch(db, batch);
334 333
                                             lastSyncedBatchId = batch.Id;
335
-                                            if (!Utility.UpdateSavedParameter(conn, "LastSyncedBatchId", lastSyncedBatchId))
334
+                                            if (!Utility.UpdateSavedParameter(db, "LastSyncedBatchId", lastSyncedBatchId))
336 335
                                             {
337 336
                                                 // Shouldn't happen.
338 337
                                                 throw new Exception("Failed to update LastSyncedBatchId");
@@ -363,9 +362,7 @@ namespace BulkPrinting
363 362
                         // Continue downloading incomplete batches if any.
364 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 367
                                 using (SQLiteDataReader row = command.ExecuteReader())
371 368
                                 {
@@ -380,11 +377,11 @@ namespace BulkPrinting
380 377
                                             if (Utility.RESTRequest(ref batch, String.Format("/api/batches/{0}", batchId)))
381 378
                                             {
382 379
                                                 refreshGrid = true;
383
-                                                Utility.SaveBatch(conn, batch);
380
+                                                Utility.SaveBatch(db, batch);
384 381
 
385 382
                                                 if (batch.ReadyForDownload)
386 383
                                                 {
387
-                                                    long result = (long)Utility.DBExecuteScalar(conn,
384
+                                                    long result = (long)db.ExecuteScalar(
388 385
                                                         "SELECT COUNT(*) FROM Voucher WHERE BatchId=@BatchId",
389 386
                                                         new SQLiteParameter("@BatchId", batchId));
390 387
                                                     int voucherCount = (int)result;
@@ -408,14 +405,14 @@ namespace BulkPrinting
408 405
 
409 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 413
                                                                     "INSERT INTO Voucher (Id, SequenceNumber, ExpiryDate, Serial, EncryptedPIN, BatchId)" +
417 414
                                                                                  "VALUES (@Id,@SequenceNumber,@ExpiryDate,@Serial,@EncryptedPin,@BatchId)",
418
-                                                                    conn, trans))
415
+                                                                    trans))
419 416
                                                                 {
420 417
                                                                     for (var i = offset; i < voucherPage.Items.Count; i++)
421 418
                                                                     {
@@ -450,7 +447,7 @@ namespace BulkPrinting
450 447
                                                     {
451 448
                                                         Log.Debug("Batch {0} complete", batchId);
452 449
 
453
-                                                        Utility.DBExecuteNonQuery(conn,
450
+                                                        db.ExecuteNonQuery(
454 451
                                                             "UPDATE Batch SET Downloaded=1 WHERE Id=@BatchId",
455 452
                                                             new SQLiteParameter("@BatchId", batchId));
456 453
                                                     }
@@ -461,11 +458,11 @@ namespace BulkPrinting
461 458
                                                 // Batch will only be null if we got a 404.
462 459
                                                 Log.Debug("Removing deleted batch {0}", batchId);
463 460
 
464
-                                                Utility.DBExecuteNonQuery(conn,
461
+                                                db.ExecuteNonQuery(
465 462
                                                     "DELETE FROM Voucher WHERE BatchId=@BatchId",
466 463
                                                     new SQLiteParameter("@BatchId", batchId));
467 464
 
468
-                                                Utility.DBExecuteNonQuery(conn,
465
+                                                db.ExecuteNonQuery(
469 466
                                                     "DELETE FROM Batch WHERE Id=@BatchId",
470 467
                                                     new SQLiteParameter("@BatchId", batchId));
471 468
 
@@ -545,7 +542,7 @@ namespace BulkPrinting
545 542
             }
546 543
 
547 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 546
                 "SELECT COUNT(*) FROM Voucher WHERE BatchId=@id",
550 547
                 new SQLiteParameter("@id", BatchID)));
551 548
             if (DownloadedVoucherCount < DeliveredVoucherCount) {
@@ -697,7 +694,7 @@ namespace BulkPrinting
697 694
                 MessageBox.Show("This batch has been exported previously. Exported batches cannot be printed.", "Cannot print batch", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
698 695
                 return;
699 696
             }
700
-            int PrintCount = int.Parse(Utility.DBExecuteScalar(Globals.DBConnection,
697
+            int PrintCount = int.Parse(Globals.DB.ExecuteScalar(
701 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 699
                 new SQLiteParameter("@batchid", BatchID),
703 700
                 new SQLiteParameter("@eventtype", VendorEvent.VendorEventType.PrintVoucher)).ToString());
@@ -708,7 +705,7 @@ namespace BulkPrinting
708 705
             }
709 706
 
710 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 709
                 "SELECT COUNT(*) FROM Voucher WHERE BatchId=@id",
713 710
                 new SQLiteParameter("@id", BatchID)));
714 711
             if (DownloadedVoucherCount < DeliveredVoucherCount)

+ 1 - 0
BulkPrinting/BulkPrinting/BulkPrinting.csproj

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

+ 111 - 0
BulkPrinting/BulkPrinting/DBHelper.cs

@@ -0,0 +1,111 @@
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,7 +49,7 @@ namespace BulkPrinting
49 49
                 Sql += " AND b.NetworkName=@networkname";
50 50
             }
51 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 54
                 if (cmbNetwork.SelectedItem.ToString() != "All")
55 55
                 {
@@ -97,7 +97,7 @@ namespace BulkPrinting
97 97
                 lblBatchType.Text = "Previously Exported Batches";
98 98
             }
99 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 102
                 cmbNetwork.Items.Clear();
103 103
                 cmbNetwork.Items.Add("All");
@@ -153,7 +153,7 @@ namespace BulkPrinting
153 153
                     List<EventLog> LogEvents = new List<EventLog>();
154 154
 
155 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 158
                         foreach (BatchItem ExportBatch in lstSelectedBatches.Items)
159 159
                         {
@@ -205,7 +205,7 @@ namespace BulkPrinting
205 205
                             }
206 206
                         }
207 207
                     }
208
-                    Utility.LogBulkEvents(Globals.DBConnection, LogEvents);
208
+                    Utility.LogBulkEvents(Globals.DB, LogEvents);
209 209
                 }
210 210
                 MessageBox.Show("Vouchers Exported");
211 211
                 this.Close();

+ 2 - 8
BulkPrinting/BulkPrinting/Globals.cs

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

+ 14 - 16
BulkPrinting/BulkPrinting/Migrations.cs

@@ -1,13 +1,11 @@
1 1
 using System;
2
-using System.Data.SQLite;
3
-using System.IO;
4 2
 
5 3
 namespace BulkPrinting
6 4
 {
7 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 9
             int startingMigration;
12 10
             if (result == null)
13 11
             {
@@ -23,26 +21,26 @@ namespace BulkPrinting
23 21
                 throw new Exception("Database is for a newer version of this application. Please upgrade and try again.");
24 22
             }
25 23
             if (startingMigration < 1) {
26
-                Migration1(conn);
24
+                Migration1(db);
27 25
             }
28 26
             if (startingMigration < 2)
29 27
             {
30
-                Migration2(conn);
28
+                Migration2(db);
31 29
             }
32 30
             //Add further migration executions here - Migration = '1', '2', '3' etc
33 31
 
34 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 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 45
                             command.ExecuteNonQuery();
48 46
                         }
@@ -53,9 +51,9 @@ namespace BulkPrinting
53 51
             return true;
54 52
         }
55 53
 
56
-        public static bool InitialVersion(SQLiteConnection conn) {
54
+        public static bool InitialVersion(DBHelper db) {
57 55
             return ApplyMigrationQueries(
58
-                conn,
56
+                db,
59 57
                 "CREATE TABLE Batch (" +
60 58
                     "Id INT," +
61 59
                     "OrderDate DATETIME," +
@@ -121,19 +119,19 @@ namespace BulkPrinting
121 119
             );
122 120
         }
123 121
 
124
-        public static bool Migration1 (SQLiteConnection conn){
122
+        public static bool Migration1 (DBHelper db){
125 123
             return ApplyMigrationQueries(
126
-                conn,
124
+                db,
127 125
                 "ALTER TABLE Orders ADD COLUMN InternalReference VARCHAR(32)",
128 126
                 "ALTER TABLE Batch ADD COLUMN InternalReference VARCHAR(32)",
129 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 133
             return ApplyMigrationQueries(
136
-                conn,
134
+                db,
137 135
                 "ALTER TABLE Batch ADD COLUMN Downloaded BOOLEAN",
138 136
                 "CREATE UNIQUE INDEX Batch_Id ON Batch(Id)",
139 137
                 "CREATE INDEX Batch_OrderDate ON Batch(OrderDate)",

+ 14 - 14
BulkPrinting/BulkPrinting/OrderForm.cs

@@ -109,22 +109,22 @@ namespace BulkPrinting
109 109
             DialogResult PlaceOrder = MessageBox.Show(OrderReviewMessage, "Proceed?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
110 110
             if (PlaceOrder == DialogResult.Yes) {
111 111
                 string InternalReference = Utility.GetNextInternalReference();
112
-                Utility.DBExecuteNonQuery(Globals.DBConnection,
112
+                Globals.DB.ExecuteNonQuery(
113 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 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 129
                             for (int i = 0; i < this.SelectedProducts.Count; i++)
130 130
                             {
@@ -149,8 +149,8 @@ namespace BulkPrinting
149 149
                 ProgressDialog Progress = new ProgressDialog();
150 150
                 Progress.Show();
151 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 155
                         Progress.UpdateProgressText("Please wait...");
156 156
                         Progress.UpdateProgressBar(0);
@@ -176,10 +176,10 @@ namespace BulkPrinting
176 176
                                 continue;
177 177
                             }
178 178
                             //TODO: Handle failed order
179
-                            Utility.SaveBatch(conn, OrderedBatch.Batch);
179
+                            Utility.SaveBatch(db, OrderedBatch.Batch);
180 180
                             SourceForm.NewBatchAvailable();
181 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 183
                             Progress.UpdateProgressBar((int)Math.Round(100 * (((decimal)i + 1) / (decimal)SelectedProducts.Count)));
184 184
                             Thread.Sleep(50);
185 185
                         }

+ 8 - 9
BulkPrinting/BulkPrinting/OrderReport.cs

@@ -36,11 +36,11 @@ namespace BulkPrinting
36 36
             dgvOrderReport.Columns.Add("DeliveredQuantity", "Delivered Quantity");
37 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 45
                 using (SQLiteDataReader read = Command.ExecuteReader())
46 46
                 {
@@ -106,12 +106,11 @@ namespace BulkPrinting
106 106
         private void btnPrint_Click(object sender, EventArgs e)
107 107
         {
108 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 114
                 int CurrentId;
116 115
                 int LastId = -1;
117 116
                 List<OrderList> Orders = new List<OrderList>();

+ 4 - 4
BulkPrinting/BulkPrinting/PrintAlignmentDialog.cs

@@ -97,7 +97,7 @@ namespace BulkPrinting
97 97
             }
98 98
             else if (NumVouchers != null)
99 99
             {
100
-                FirstVoucherSequenceNumber = Convert.ToInt32(Utility.DBExecuteScalar(Globals.DBConnection,
100
+                FirstVoucherSequenceNumber = Convert.ToInt32(Globals.DB.ExecuteScalar(
101 101
                     "SELECT MIN(v.SequenceNumber) FROM Voucher v " +
102 102
                         "LEFT JOIN Logs l ON v.Id = l.VoucherId AND l.EventType = @eventtype " +
103 103
                         "WHERE v.BatchId = @batchid AND l.id IS NULL",
@@ -117,10 +117,10 @@ namespace BulkPrinting
117 117
             this.Enabled = false;
118 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 124
                     Globals.OpenBatches.Remove(BatchID);
125 125
                     this.Invoke((Action)(() =>
126 126
                     {

+ 1 - 1
BulkPrinting/BulkPrinting/PrintForm.cs

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

+ 7 - 6
BulkPrinting/BulkPrinting/ReprintForm.cs

@@ -44,10 +44,11 @@ namespace BulkPrinting
44 44
             lblFaceValue.Text = FaceValue;
45 45
             lblVoucherType.Text = VoucherTypeName;
46 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 52
                 using (SQLiteDataReader read = Command.ExecuteReader())
52 53
                 {
53 54
                     read.Read();
@@ -100,7 +101,7 @@ namespace BulkPrinting
100 101
                 SelectedRangeEnd = (int)numLastSeqNum.Value;
101 102
             }
102 103
             else if (rdoSerial.Checked) {
103
-                int PrintCount = int.Parse(Utility.DBExecuteScalar(Globals.DBConnection,
104
+                int PrintCount = int.Parse(Globals.DB.ExecuteScalar(
104 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 106
                     new SQLiteParameter("@serialnum", txtSerialNum.Text),
106 107
                     new SQLiteParameter("@eventtype", VendorEvent.VendorEventType.PrintVoucher)).ToString());
@@ -111,11 +112,11 @@ namespace BulkPrinting
111 112
             }
112 113
 
113 114
             VoucherCount = SelectedRangeEnd - SelectedRangeStart + 1;
114
-            decimal VoucherFaceValue = (decimal)Utility.DBExecuteScalar(Globals.DBConnection,
115
+            decimal VoucherFaceValue = (decimal)Globals.DB.ExecuteScalar(
115 116
                 "SELECT FaceValue FROM Batch WHERE Id=@id",
116 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 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 121
                 new SQLiteParameter("@event", (int) VendorEvent.VendorEventType.PrintVoucher),
121 122
                 new SQLiteParameter("@batchid", BatchID),

+ 10 - 10
BulkPrinting/BulkPrinting/UserLoginForm.cs

@@ -60,11 +60,11 @@ namespace BulkPrinting
60 60
                 }
61 61
                 else
62 62
                 {
63
-                    Globals.DBConnection = Utility.OpenDBConnection();
63
+                    Globals.DB = Utility.OpenDBConnection();
64 64
                     //Test login success
65 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 68
                     Globals.SessionVoucherKey = Utility.AesDecryptBytes(Globals.SessionData.Credentials.Payload.EncryptedVoucherKey, userKey);
69 69
                     DateTime ServerDate = Globals.SessionData.Credentials.Payload.Date;
70 70
                     DateTime Today = DateTime.Now;
@@ -72,7 +72,7 @@ namespace BulkPrinting
72 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 73
                         return;
74 74
                     }
75
-                    Utility.LogEvent(Globals.DBConnection, VendorEvent.VendorEventType.OfflineLogin);
75
+                    Utility.LogEvent(Globals.DB, VendorEvent.VendorEventType.OfflineLogin);
76 76
                     LoginSuccessful = true;
77 77
                 }
78 78
             }
@@ -113,15 +113,15 @@ namespace BulkPrinting
113 113
                                 Directory.CreateDirectory(Globals.MaxDBPath);
114 114
                             }
115 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 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 125
                         Utility.TriggerLogDownload();
126 126
                         Utility.TriggerLogUpload();
127 127
                     }
@@ -146,7 +146,7 @@ namespace BulkPrinting
146 146
                 Globals.SessionData.Credentials.Payload.User.OnlineReprintValue = 0;
147 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 150
                 Globals.MaxPrinter = new Printer();
151 151
                 this.txtPassword.Text = "";
152 152
                 this.Hide();

+ 89 - 122
BulkPrinting/BulkPrinting/Utility.cs

@@ -46,39 +46,9 @@ namespace BulkPrinting
46 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 54
         public static bool Login(LoginData UserLoginData, bool Offline, bool RememberMe) {
@@ -334,16 +304,14 @@ namespace BulkPrinting
334 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 315
                         command.Parameters.AddWithValue("@Id", batch.Id);
348 316
                         command.Parameters.AddWithValue("@OrderDate", batch.OrderDate);
349 317
                         command.Parameters.AddWithValue("@OrderGuid", batch.OrderGuid);
@@ -383,31 +351,31 @@ namespace BulkPrinting
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 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 373
                 "UPDATE Parameters SET Value=@Value WHERE Key=@Key",
406 374
                 new SQLiteParameter("@Key", key),
407 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 381
             int VoucherCount = 0;
@@ -427,13 +395,12 @@ namespace BulkPrinting
427 395
             List<EventLog> LogEvents = new List<EventLog>();
428 396
 
429 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 404
                 using (SQLiteDataReader read = Command.ExecuteReader())
438 405
                 {
439 406
                     int JobID = Globals.MaxPrinter.Open("Vouchers");
@@ -515,7 +482,7 @@ namespace BulkPrinting
515 482
                     Globals.MaxPrinter.Close();
516 483
                 }
517 484
             }
518
-            LogBulkEvents(conn, LogEvents);
485
+            LogBulkEvents(db, LogEvents);
519 486
         }
520 487
 
521 488
         public enum UserPermissions {
@@ -558,13 +525,13 @@ namespace BulkPrinting
558 525
         public static void Logout() {
559 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 529
                 string SessionDataJson = JsonConvert.SerializeObject(Globals.SessionData);
563
-                DBExecuteNonQuery(Globals.DBConnection,
530
+                Globals.DB.ExecuteNonQuery(
564 531
                     "INSERT INTO SessionData (Key,Value) VALUES (@key,@value)",
565 532
                     new SQLiteParameter("@key", "SessionDataJson"),
566 533
                     new SQLiteParameter("@value", SessionDataJson));
567
-                LogEvent(Globals.DBConnection, VendorEvent.VendorEventType.Logout);
534
+                LogEvent(Globals.DB, VendorEvent.VendorEventType.Logout);
568 535
 
569 536
                 CancelLogUploadWorker();
570 537
                 CancelLogDownloadWorker();
@@ -581,8 +548,12 @@ namespace BulkPrinting
581 548
                 }
582 549
 
583 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 557
                 Globals.SessionData = null;
587 558
                 Globals.SessionDatabasePassword = null;
588 559
                 Globals.SessionVoucherKey = null;
@@ -603,32 +574,29 @@ namespace BulkPrinting
603 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 581
                 var lastSyncedLogId = GetLastSyncedLogID();
611 582
 
612 583
                 // If we already have logs then there is no need to synchronise.
613 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 590
                 // If there are logs on the server then ensure that the log autoincrement value is set to the last
620 591
                 // log ID received by the server so new local logs don't clash with existing log entries on the server.
621 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 600
                                 command.CommandText = "UPDATE sqlite_sequence SET seq=CASE WHEN IFNULL(seq, 0)<@Id THEN @Id ELSE seq END WHERE name='Logs'";
633 601
                                 if (command.ExecuteNonQuery() == 0)
634 602
                                 {
@@ -641,7 +609,7 @@ namespace BulkPrinting
641 609
                     }
642 610
                 }
643 611
 
644
-                UpdateSavedParameter(conn, "LoggingInitialised", true);
612
+                UpdateSavedParameter(db, "LoggingInitialised", true);
645 613
             }
646 614
         }
647 615
 
@@ -659,27 +627,26 @@ namespace BulkPrinting
659 627
             const int vendorEventPageSize = 1000;
660 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 633
                 bool cancelled = false;
666
-                int maxRemoteId = GetSavedParameterAsInt(conn, "SyncBackwardsFromLogId");
634
+                int maxRemoteId = GetSavedParameterAsInt(db, "SyncBackwardsFromLogId");
667 635
                 while (!cancelled && (maxRemoteId > 0))
668 636
                 {
669 637
                     var EventPage = new Page<VendorEvent>();
670 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 645
                                     "INSERT INTO Logs (Id,  UserId,  VoucherId,  EventDate,  EventType,  Retry) " +
678 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 651
                                     foreach (VendorEvent Event in EventPage.Items)
685 652
                                     {
@@ -756,8 +723,8 @@ namespace BulkPrinting
756 723
             const int uploadPageSize = 1000;
757 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 729
                 var cancelled = false;
763 730
                 while (! cancelled)
@@ -765,7 +732,7 @@ namespace BulkPrinting
765 732
                     var uploadFailed = false;
766 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 736
                     if (string.IsNullOrWhiteSpace(result))
770 737
                     {
771 738
                         result = "0";
@@ -776,9 +743,9 @@ namespace BulkPrinting
776 743
                     {
777 744
                         List<RemoteVendorEvent> eventList = new List<RemoteVendorEvent>();
778 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 749
                             using (SQLiteDataReader read = Command.ExecuteReader())
783 750
                             {
784 751
                                 while (read.Read())
@@ -818,7 +785,7 @@ namespace BulkPrinting
818 785
                                 if (counter > 0)
819 786
                                 {
820 787
                                     var response = new RemoteVendorEventResponse();
821
-                                    if (! RESTRequest(eventList, ref response, "/api/vendorevents/"))
788
+                                    if (!RESTRequest(eventList, ref response, "/api/vendorevents/"))
822 789
                                     {
823 790
                                         uploadFailed = true;
824 791
                                     }
@@ -861,15 +828,15 @@ namespace BulkPrinting
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 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 841
                         foreach (var EventLog in EventLogs)
875 842
                         {
@@ -892,9 +859,9 @@ namespace BulkPrinting
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 865
                 "INSERT INTO Logs (UserId,  VoucherId,  EventDate,  EventType,  Retry) " +
899 866
                           "VALUES (@userid, @voucherid, @eventdate, @eventtype, @retry)",
900 867
                 new SQLiteParameter("@userid", Globals.SessionData.Credentials.Payload.User.Id),
@@ -908,12 +875,12 @@ namespace BulkPrinting
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 880
                 "DELETE FROM AccessControlTracking WHERE UserID = @userid",
914 881
                 new SQLiteParameter("@userid", Globals.SessionData.Credentials.Payload.User.Id));
915 882
 
916
-            DBExecuteNonQuery(conn,
883
+            db.ExecuteNonQuery(
917 884
                 "INSERT INTO AccessControlTracking (UserID, Date, Permission, CurrentUsage) VALUES " +
918 885
                     "(@userid, datetime('now'), 'OfflinePrint', @offlineprintvalue)," +
919 886
                     "(@userid, datetime('now'), 'OfflineReprint', @offlinereprintvalue)," +
@@ -930,7 +897,7 @@ namespace BulkPrinting
930 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 901
             DateTime ServerDate = Globals.SessionData.Credentials.Payload.Date;
935 902
             DateTime Today = DateTime.Now;
936 903
             if (ServerDate.Date != Today.Date) //prevent system time tampering
@@ -961,7 +928,7 @@ namespace BulkPrinting
961 928
             }
962 929
 
963 930
             //Immediately write to db to avoid cheating
964
-            SaveCurrentUserUsage(conn);
931
+            SaveCurrentUserUsage(db);
965 932
         }
966 933
 
967 934
         public static Boolean IsValueWithinRemainingUserLimit(UserLimits.UserLimitTypes UserLimitType, decimal Value) {
@@ -1080,31 +1047,31 @@ namespace BulkPrinting
1080 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 1053
                 "SELECT COUNT(*) FROM Logs WHERE VoucherId=@voucherid AND EventType=@eventtype",
1087 1054
                 new SQLiteParameter("@voucherid", VoucherId),
1088 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 1061
                 "SELECT MIN(EventDate) FROM Logs WHERE VoucherId=@voucherid AND EventType=@eventtype",
1095 1062
                 new SQLiteParameter("@voucherid", VoucherId),
1096 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 1069
                 "SELECT b.FaceValue FROM Voucher v LEFT JOIN Batch b on v.BatchId = b.Id WHERE v.Id=@voucherid",
1103 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 1075
             UserLimits CalculateUsage = new UserLimits();
1109 1076
             CalculateUsage.OfflinePrintValue = 0;
1110 1077
             CalculateUsage.OfflineReprintValue = 0;
@@ -1113,12 +1080,12 @@ namespace BulkPrinting
1113 1080
             var CurrentDate = DateTime.Today.Date;
1114 1081
             CultureInfo IVC = CultureInfo.InvariantCulture;
1115 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 1089
                 int VoucherId;
1123 1090
                 decimal VoucherFaceValue;
1124 1091
                 using (SQLiteDataReader read = Command.ExecuteReader())
@@ -1126,11 +1093,11 @@ namespace BulkPrinting
1126 1093
                     while (read.Read())
1127 1094
                     {
1128 1095
                         VoucherId = read.GetInt32(0);
1129
-                        VoucherFaceValue = GetVoucherFaceValue(conn, VoucherId);
1096
+                        VoucherFaceValue = GetVoucherFaceValue(db, VoucherId);
1130 1097
                         //Don't distinguish between online and offline usage for log recalculations
1131 1098
                         CalculateUsage.OfflinePrintValue += VoucherFaceValue;
1132 1099
                         CalculateUsage.OnlinePrintValue += VoucherFaceValue;
1133
-                        if (GetVoucherPrintCountFromLogs(conn, VoucherId) > 1)
1100
+                        if (GetVoucherPrintCountFromLogs(db, VoucherId) > 1)
1134 1101
                         { //For reprinted vouchers just assume all prints were reprints - log recalculations should be stricter to prevent cheating
1135 1102
                             CalculateUsage.OfflineReprintValue += VoucherFaceValue;
1136 1103
                             CalculateUsage.OnlineReprintValue += VoucherFaceValue;
@@ -1141,16 +1108,16 @@ namespace BulkPrinting
1141 1108
             return CalculateUsage;
1142 1109
         }
1143 1110
 
1144
-        public static void InitialiseUserLimits(SQLiteConnection conn)
1111
+        public static void InitialiseUserLimits(DBHelper db)
1145 1112
         {
1146 1113
             Globals.UserCurrentUsage = new UserLimits();
1147 1114
             UserLimits CurrentUserLimits = new UserLimits();
1148 1115
 
1149
-            int Result = int.Parse(DBExecuteScalar(conn,
1116
+            int Result = int.Parse(db.ExecuteScalar(
1150 1117
                 "SELECT COUNT(*) FROM AccessControlTracking WHERE UserID = @userid",
1151 1118
                 new SQLiteParameter("@userid", Globals.SessionData.Credentials.Payload.User.Id)).ToString());
1152 1119
 
1153
-            object ResultDate = DBExecuteScalar(conn,
1120
+            object ResultDate = db.ExecuteScalar(
1154 1121
                 "SELECT Date FROM AccessControlTracking WHERE UserID = @userid",
1155 1122
                 new SQLiteParameter("@userid", Globals.SessionData.Credentials.Payload.User.Id));
1156 1123
 
@@ -1163,17 +1130,17 @@ namespace BulkPrinting
1163 1130
             }
1164 1131
             if (DatePassed)
1165 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 1136
             else
1170 1137
             {
1171 1138
                 if (Result == 6)
1172 1139
                 {
1173 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 1144
                         using (SQLiteDataReader read = Command.ExecuteReader())
1178 1145
                         {
1179 1146
                             while (read.Read())
@@ -1205,17 +1172,17 @@ namespace BulkPrinting
1205 1172
                 }
1206 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 1182
             int UnprintedVouchers = 0;
1216 1183
             int VoucherId;
1217 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 1187
                 for (int SeqNo = StartSeqNo; SeqNo <= EndSeqNo; SeqNo++)
1221 1188
                 {
@@ -1223,7 +1190,7 @@ namespace BulkPrinting
1223 1190
                     Command.Parameters.AddWithValue("@sequencenumber", SeqNo);
1224 1191
                     Command.Parameters.AddWithValue("@batchid", BatchId);
1225 1192
                     VoucherId = int.Parse(Command.ExecuteScalar().ToString());
1226
-                    int NumPrintedVouchers = GetVoucherPrintCountFromLogs(conn, VoucherId);
1193
+                    int NumPrintedVouchers = GetVoucherPrintCountFromLogs(db, VoucherId);
1227 1194
                     if (NumPrintedVouchers == 0)
1228 1195
                     {
1229 1196
                         UnprintedVouchers++;

+ 1 - 1
BulkPrinting/BulkPrinting/VoucherForm.cs

@@ -52,7 +52,7 @@ namespace BulkPrinting
52 52
 
53 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 57
                 if (rdoPrintDate.Checked)
58 58
                 {