forked from KevinSchott/SecondSight
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSSDataBase.cs
More file actions
2172 lines (1986 loc) · 100 KB
/
SSDataBase.cs
File metadata and controls
2172 lines (1986 loc) · 100 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2009, 2010, 2011 Kevin Schott
// This file is part of SecondSight.
// SecondSight is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// SecondSight is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with SecondSight. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Data.SQLite;
using System.IO;
using System.Text;
namespace SecondSight
{
#region Support Structs and Enums
public enum SSTable { Current, Dispensed, DBInfo, MergeInfo, MergeItems }
#endregion
public class SSDataBase
{
//Constants
private const int NUM_SEARCH_PARAMS = 21;
private const float SCORE_THRESHOLD = 2.5F;
private static readonly string[] RLIMITS_FILTERSTRING = new string[]
{"SKU", "SphereOD", "CylinderOD", "AxisOD", "AddOD",
"SphereOS", "CylinderOS", "AxisOS", "AddOS",
"Type", "Gender", "Size", "Tint", "DateAdded", "DateDispensed"};
//Member variables
private string DBPath;
private SQLiteConnection DBConn;
private SQLiteCommand DBcmd;
private SQLiteParameter[] DBParams;
private SQLiteParameter[] Sparams; //Search parameters
private DataTable dbresults, tresults; //tresults used for split multifocals only
private DataTable invresults; //Inventory results - used for full inventory display
public DataTable DBResults { get { return dbresults; } }
public DataTable DBResultsAux { get { return tresults; } }
public DataTable InvResults { get { return invresults; } }
public string MyPath { get { return DBPath; } }
#region Member Functions
/// <summary>
/// Creates a new database and populates it with the appropriate SecondSight tables
/// </summary>
/// <remarks>Only used when the file does not already exist (Use OpenDB for existing files)</remarks>
/// <param name="path">The full file path to the new database</param>
/// <param name="dbname">The name of the database</param>
/// <param name="dblocation">The physical location of the database (where the physical inventory is and/or where the clinic is held)</param>
/// <exception cref="System.IO.IOException">Thrown when the file already exists</exception>
public void CreateNewDB(string path, string dbname, string dblocation)
{
if (File.Exists(path))
throw new IOException(String.Format("File already exists: {0}", path));
//Close the currently open connection and clear the data tables
DBConn.Close();
dbresults.Clear();
tresults.Clear();
invresults.Clear();
//File doesn't exist, create and configure
DBPath = path;
DBConn.ConnectionString = new SQLiteConnectionStringBuilder(String.Format(@"Data Source={0}", DBPath)).ConnectionString;
DBConn.Open();
using (SQLiteTransaction dbt = DBConn.BeginTransaction())
{
//This table has a unique integer, SKU, but it is not the primary key because the
//SKU numbers are reused from year to year in a fixed-size inventory.
//Instead, the primary key is the special SQLite column ROWID
DBcmd.CommandText = "CREATE TABLE CurrentInventory(SKU INTEGER UNIQUE, SphereOD REAL, " +
"CylinderOD REAL, AxisOD INTEGER, AddOD REAL, SphereOS REAL, CylinderOS REAL, " +
"AxisOS INTEGER, AddOS REAL, Type TEXT, Gender TEXT, Size TEXT, " +
"Tint TEXT, DateAdded DATETIME, Comment TEXT)";
DBcmd.ExecuteNonQuery();
//This table is not indexed by SKU, since it could have entries from multiple years, thus duplicate SKUs.
//Table does not use a compound primary key (SKU, Date) because SQLite searches much faster with an
//integer primary key. (The primary key is ROWID, a special column name in SQLite).
DBcmd.CommandText = "CREATE TABLE DispensedInventory(SKU INTEGER, SphereOD REAL, " +
"CylinderOD REAL, AxisOD INTEGER, AddOD REAL, SphereOS REAL, CylinderOS REAL, " +
"AxisOS INTEGER, AddOS REAL, Type TEXT, Gender TEXT, Size TEXT, " +
"Tint TEXT, DateAdded DATETIME, DateDispensed DATETIME, Comment TEXT)";
DBcmd.ExecuteNonQuery();
//Table contains a single field, used for database information
DBcmd.CommandText = "CREATE TABLE DBInfo(Name TEXT, Location TEXT, DateCreated DATETIME)";
DBcmd.ExecuteNonQuery();
//Insert information field
DBcmd.CommandText = @"INSERT INTO DBInfo VALUES(@pdbname, @pdbloc, @pdbdate)";
DBParams[16].Value = dbname;
DBParams[17].Value = dblocation;
DBParams[18].Value = String.Format("{0:yyyy-MM-dd}", DateTime.Now);
DBcmd.ExecuteNonQuery();
//This table holds duplicate records - only used when importing a database from REIMS
DBcmd.CommandText = "CREATE TABLE DupedInventory(SKU INTEGER UNIQUE, SphereOD REAL, " +
"CylinderOD REAL, AxisOD INTEGER, AddOD REAL, SphereOS REAL, CylinderOS REAL, " +
"AxisOS INTEGER, AddOS REAL, Type TEXT, Gender TEXT, Size TEXT, " +
"Tint TEXT, DateAdded DATETIME, Comment TEXT)";
DBcmd.ExecuteNonQuery();
dbt.Commit(); //Commit the transaction
}
return;
}
/// <summary>
/// Opens an existing database file.
/// <remarks>Should be called on init and whenever the user attempts to open a different database.</remarks>
/// </summary>
/// <param name="path">The full file path of the database file to open</param>
/// <exception cref="System.IO.FileNotFoundException">Thrown when the file to open does not exist</exception>
/// <exception cref="System.Data.SQLite.SQLiteException">Thrown when the file is not a valid SecondSight database</exception>
public void OpenDB(string path)
{
//Check if the file exists
if (!File.Exists(path))
throw new FileNotFoundException("File not found.");
//Close the currently open connection
DBConn.Close();
DBPath = path;
DBConn.ConnectionString = new SQLiteConnectionStringBuilder(String.Format(@"Data Source={0}", DBPath)).ConnectionString;
try
{
DBConn.Open();
}
catch (SQLiteException sqlex)
{
throw new SQLiteException("File is not a valid SecondSight database.", sqlex.InnerException);
}
//Check to make sure this is a valid SecondSight database
DataTable sdt = DBConn.GetSchema("Tables");
try
{
if (!((string)sdt.Rows[0][2] == "CurrentInventory"
&& (string)sdt.Rows[1][2] == "DispensedInventory"
&& (string)sdt.Rows[2][2] == "DBInfo"
&& (string)sdt.Rows[3][2] == "DupedInventory"))
{
throw new SQLiteException("File is not a valid SecondSight database.");
}
}
catch (IndexOutOfRangeException e)
{
throw new SQLiteException("File is not a valid SecondSight database.", e.InnerException);
}
sdt.Reset();
sdt = DBConn.GetSchema("Columns");
try
{
if (sdt.Rows[13][11].ToString() == "text")
{ //Old DB format for dates, update and convert
DBConvert(0);
}
else if (sdt.Rows[13][11].ToString() != "datetime")
{//Not old format, not new format, so unknown format
throw new SQLiteException("File is not a valid SecondSight database.");
}
}
catch (IndexOutOfRangeException)
{ //Should never get here
throw new SQLiteException("File is not a valid SecondSight database.");
}
}
/// <summary>
/// Close the currently open database.
/// </summary>
/// <exception cref="System.Exception">Thrown when the database could not be closed.</exception>
public void CloseDB()
{
try
{
DBConn.Close();
invresults.Clear();
dbresults.Clear();
tresults.Clear();
}
catch (Exception e)
{
throw new Exception("Could not close database.", e.InnerException);
}
}
/// <summary>
/// Search using pre-determined parameters.
/// </summary>
/// <param name="sprec">The paramaters to search by</param>
/// <param name="deye">The dominant eye</param>
/// <param name="splitmf">Whether or not to split a multifocal search into two searches - Distance and Closeup</param>
public void RxSearch(SpecsRecord sprec, DomEye deye, bool splitmf)
{
//Clear results for the search
dbresults.Clear();
tresults.Clear();
//Split multifocals: two searches, back to back, for single vision glasses.
//First search is for specified sphere power, second is for sphere power + add power
if (splitmf)
{
float odadd, osadd;
odadd = sprec.AddOD;
osadd = sprec.AddOS;
sprec.AddOD = 0;
sprec.AddOS = 0;
sprec.Type = SpecType.Single;
RxSearchRange(sprec, deye, dbresults); //Search for first set of matches
RxScoreResults(sprec, deye, dbresults); //Rank the matches
sprec.SphereOD += odadd;
sprec.SphereOS += osadd;
RxSearchRange(sprec, deye, tresults); //Search for second set of matches
RxScoreResults(sprec, deye, tresults); //Rank the matches
}
else
{
RxSearchRange(sprec, deye, dbresults); //Search for possible matches
RxScoreResults(sprec, deye, dbresults); //Rank the matches
}
}
/// <summary>
/// Inserts a single record into the database into a specified table. Not all tables are valid and
/// an exception will be thrown if an invalid destination table is specified
/// </summary>
/// <param name="sprec">The pre-built SpecsRecord to insert</param>
/// <param name="_table">The table to insert the record into</param>
public void Insert(SpecsRecord sprec, SSTable _table)
{
string destination = "";
if (_table == SSTable.Current)
{
destination = "CurrentInventory";
}
else if (_table == SSTable.MergeItems)
{
destination = "MergeItems";
}
DBcmd.CommandText = @"INSERT INTO " + destination + @" VALUES(@psku, @psod, @pcod, @paxod, " +
@"@padod, @psos, @pcos, @paxos, @pados, @ptype, @pgen, @psize, @ptint, @padate, @pcom)";
//DBcmd.CommandText = @"INSERT INTO CurrentInventory VALUES(@psku, @psod, @pcod, @paxod, " +
// @"@padod, @psos, @pcos, @paxos, @pados, @ptype, @pgen, @psize, @ptint, @padate, @pcom)";
DBParams[0].Value = sprec.SKU;
DBParams[1].Value = sprec.SphereOD;
DBParams[2].Value = sprec.CylOD;
DBParams[3].Value = sprec.AxisOD;
DBParams[4].Value = sprec.AddOD;
DBParams[5].Value = sprec.SphereOS;
DBParams[6].Value = sprec.CylOS;
DBParams[7].Value = sprec.AxisOS;
DBParams[8].Value = sprec.AddOS;
DBParams[9].Value = sprec.Type;
DBParams[10].Value = sprec.Gender;
DBParams[11].Value = sprec.Size;
DBParams[12].Value = sprec.Tint;
DBParams[13].Value = sprec.DateAdded;
DBParams[15].Value = sprec.Comment;
try
{
DBcmd.ExecuteNonQuery();
}
catch (InvalidOperationException ioe)
{
throw new InvalidOperationException(ioe.Message, ioe.InnerException);
}
catch (SQLiteException sqle)
{
throw new SQLiteException(sqle.Message, sqle.InnerException);
}
}
//Imports data from an old REIMS FoxPro database into the current database
//path - the directory path for GLSKU.DBF and DISPENSE.DBF
//These file names are mandatory
//This function should only be used with a fresh (empty) SecondSight database
/// <summary>
/// Imports data from an old REIMS Visual FoxPro database into the the current SecondSight database
/// </summary>
/// <param name="path">The full directory path to GLSKU.DBF and DISPENSE.DBF</param>
/// <exception cref="System.IO.FileNotFoundException">Thrown when one of the mandatory FoxPro files is not found</exception>
/// <exception cref="System.Data.SQLite.SQLiteException">Thrown when a duplicate SKU is found when adding to the CurrentInventory table</exception>
/// <exception cref="System.Data.SQLite.SQLiteException">Thrown when a record cannot be entered into the DupedInventory table</exception>
/// <exception cref="System.Data.SQLite.SQLiteException">Thrown when a record cannot be entered into the DispensedInventory table</exception>
public void ImportREIMS(string path)
{
//Check for GLSKU.DBF and DISPENSE.DBF
if (!File.Exists(path + "GLSKU.DBF"))
throw new FileNotFoundException("File Not Found", "GLSKU.DBF");
if (!File.Exists(path + "DISPENSE.DBF"))
throw new FileNotFoundException("File Not Found", "DISPENSE.DBF");
//Set up the FoxPro connection and transfer medium data set
DataTable rdt = new DataTable();
#region Current Inventory Import
using (OleDbConnection rcnn = new OleDbConnection(
String.Format(@"Provider=vfpoledb;Data Source={0} ;Collating Sequence=general;", path)))
{
using (OleDbCommand rcmd = rcnn.CreateCommand())
{
OleDbDataAdapter rda;
rcmd.Connection = rcnn;
//Populate the Data Set and close the FoxPro database
rcnn.Open();
rcmd.CommandText = @"SELECT * FROM GLSKU";
rda = new OleDbDataAdapter(rcmd);
rda.Fill(rdt);
}
}
//String processing for every record in the table
//Trims out all the unnecessary characters from the SKU and fills in any blank fields with default values
for (int i = 0; i < rdt.Rows.Count; i++)
{
String temp = rdt.Rows[i][0].ToString();
temp = temp.Substring(temp.IndexOf(":") + 1);
rdt.Rows[i][0] = temp.Substring(0, temp.IndexOf(" "));
//Type - Sets any blanks to S and changes B(ifcoal) to M(ultifocal)
if (rdt.Rows[i][1].ToString() == " ")
rdt.Rows[i][1] = "S";
else if (rdt.Rows[i][1].ToString() == "B")
rdt.Rows[i][1] = "M";
//Gender - Sets any blanks to unisex (U)
if (rdt.Rows[i][10].ToString() == " ")
rdt.Rows[i][10] = "U";
//Size - Sets any blanks to medium (M)
if (rdt.Rows[i][12].ToString() == " ")
rdt.Rows[i][12] = "M";
//Tint - Sets any blanks to none (N)
if (rdt.Rows[i][13].ToString() == " ")
rdt.Rows[i][13] = "N";
//Date - Sets any blank date to January 01, 2000 (01/01/00)
if (rdt.Rows[i][14].ToString() == " ")
rdt.Rows[i][14] = "01/01/00";
}
ArrayList duperec = new ArrayList(); //Will be an array of DataRow objects
//This section is responsible for copying the values from the DataTable
//to the SecondSight database
//Import into CurrentInventory
using (SQLiteTransaction dbt = DBConn.BeginTransaction()) //Transaction wrapper for bulk insert
{
DBcmd.CommandText = @"INSERT INTO CurrentInventory VALUES(@psku, @psod, @pcod, @paxod, @padod, " +
@"@psos, @pcos, @paxos, @pados, @ptype, @pgen, @psize, @ptint, @padate, @pcom)";
DBParams[15].Value = ""; //Comment field - not present in REIMS database
//Sets parameter values and executes a single insert. Happens once for every record
//in the GLSKU table from REIMS
for (int i = 0; i < rdt.Rows.Count; i++)
{
DBParams[0].Value = rdt.Rows[i][0];
DBParams[1].Value = rdt.Rows[i][2];
DBParams[2].Value = rdt.Rows[i][3];
DBParams[3].Value = rdt.Rows[i][4];
DBParams[4].Value = rdt.Rows[i][5];
DBParams[5].Value = rdt.Rows[i][6];
DBParams[6].Value = rdt.Rows[i][7];
DBParams[7].Value = rdt.Rows[i][8];
DBParams[8].Value = rdt.Rows[i][9];
DBParams[9].Value = rdt.Rows[i][1];
DBParams[10].Value = rdt.Rows[i][10];
DBParams[11].Value = rdt.Rows[i][12];
DBParams[12].Value = rdt.Rows[i][13];
DBParams[13].Value = rdt.Rows[i][14];
try
{
DBcmd.ExecuteNonQuery();
}
catch (SQLiteException e)
{
if (e.ErrorCode == SQLiteErrorCode.Constraint) //Dupicate SKU
{
//Add record to an arraylist so they can later be inserted into
//the dupes table
duperec.Add(rdt.Rows[i]);
}
}
}
dbt.Commit();
}
#endregion
#region Duped Inventory Storage
using (SQLiteTransaction dbt = DBConn.BeginTransaction())
{
DBcmd.CommandText = @"INSERT INTO DupedInventory VALUES(@psku, @psod, @pcod, @paxod, @padod, " +
@"@psos, @pcos, @paxos, @pados, @ptype, @pgen, @psize, @ptint, @padate, @pcom)";
DBParams[15].Value = ""; //Comment field - not present in REIMS database
//Sets parameter values and executes a single insert. Happens once for ever duplicate SKU
//that was found in GLSKU.DBF from REIMS
for (int i = 0; i < duperec.Count; i++)
{
DBParams[0].Value = ((DataRow)duperec[i])[0];
DBParams[1].Value = ((DataRow)duperec[i])[2];
DBParams[2].Value = ((DataRow)duperec[i])[3];
DBParams[3].Value = ((DataRow)duperec[i])[4];
DBParams[4].Value = ((DataRow)duperec[i])[5];
DBParams[5].Value = ((DataRow)duperec[i])[6];
DBParams[6].Value = ((DataRow)duperec[i])[7];
DBParams[7].Value = ((DataRow)duperec[i])[8];
DBParams[8].Value = ((DataRow)duperec[i])[9];
DBParams[9].Value = ((DataRow)duperec[i])[1];
DBParams[10].Value = ((DataRow)duperec[i])[10];
DBParams[11].Value = ((DataRow)duperec[i])[12];
DBParams[12].Value = ((DataRow)duperec[i])[13];
DBParams[13].Value = ((DataRow)duperec[i])[14];
try
{
DBcmd.ExecuteNonQuery();
}
catch (SQLiteException e)
{
throw e;
}
}
dbt.Commit();
}
#endregion
#region Dispensed Inventory Import
rdt.Clear();
using (OleDbConnection rcnn = new OleDbConnection(
String.Format(@"Provider=vfpoledb;Data Source={0} ;Collating Sequence=general;", path)))
{
using (OleDbCommand rcmd = rcnn.CreateCommand())
{
OleDbDataAdapter rda;
rcmd.Connection = rcnn;
//Populate the Data Set and close the FoxPro database
rcnn.Open();
rcmd.CommandText = @"SELECT * FROM DISPENSE";
rda = new OleDbDataAdapter(rcmd);
rda.Fill(rdt);
}
}
//String processing for every record in the table
//Trims out all the unnecessary characters from the SKU and fills in any blank fields with default values
for (int i = 0; i < rdt.Rows.Count; i++)
{
String temp = rdt.Rows[i][0].ToString();
temp = temp.Substring(temp.IndexOf(":") + 1);
rdt.Rows[i][0] = temp.Substring(0, temp.IndexOf(" "));
//Gender - Sets any blanks to unisex (U)
if (rdt.Rows[i][10].ToString() == " ")
rdt.Rows[i][10] = "U";
//Size - Sets any blanks to medium (M)
if (rdt.Rows[i][12].ToString() == " ")
rdt.Rows[i][12] = "M";
//Tint - Sets any blanks to none (N)
if (rdt.Rows[i][13].ToString() == " ")
rdt.Rows[i][13] = "N";
//Date - Sets any blank date to January 01, 2000 (01/01/00)
if (rdt.Rows[i][14].ToString() == " ")
rdt.Rows[i][14] = "01/01/00";
}
//Import into DispensedInventory
using (SQLiteTransaction dbt = DBConn.BeginTransaction())
{
DBcmd.CommandText = @"INSERT INTO DispensedInventory VALUES(@psku, @psod, @pcod, @paxod, @padod, " +
@"@psos, @pcos, @paxos, @pados, @ptype, @pgen, @psize, @ptint, @padate, @pddate, @pcom)";
DBParams[15].Value = ""; //Comment field - not present in REIMS database
//Sets parameter values and executes a single insert. Happens once for every record
//in the DISPENSE table from REIMS
for (int i = 0; i < rdt.Rows.Count; i++)
{
DBParams[0].Value = rdt.Rows[i][0];
DBParams[1].Value = rdt.Rows[i][2];
DBParams[2].Value = rdt.Rows[i][3];
DBParams[3].Value = rdt.Rows[i][4];
DBParams[4].Value = rdt.Rows[i][5];
DBParams[5].Value = rdt.Rows[i][6];
DBParams[6].Value = rdt.Rows[i][7];
DBParams[7].Value = rdt.Rows[i][8];
DBParams[8].Value = rdt.Rows[i][9];
DBParams[9].Value = rdt.Rows[i][1];
DBParams[10].Value = rdt.Rows[i][10];
DBParams[11].Value = rdt.Rows[i][12];
DBParams[12].Value = rdt.Rows[i][13];
DBParams[13].Value = rdt.Rows[i][14];
DBParams[14].Value = rdt.Rows[i][14]; //Dispensed Date - not present in REIMS so set = add date
try
{
DBcmd.ExecuteNonQuery();
}
catch (SQLiteException e)
{
throw e;
}
}
dbt.Commit();
}
#endregion
}
/// <summary>
/// Dispenses glasses. Moves a record from the CurrentInventory table to the DispensedInventory table
/// </summary>
/// <param name="sprec">A valid SpecsRecord populated by data from the CurrentInventory table</param>
/// <param name="ismain">Used to distinguish between main and auxiliary tables for a split multifocals search</param>
/// <exception cref="System.Exception">Thrown when a record could not be inserted into DispensedInventory or deleted from CurrentInventory</exception>
public void Dispense(SpecsRecord sprec, bool ismain)
{
//Make a copy of the record described by sprec to the DispensedInventory table
DBcmd.CommandText = @"INSERT INTO DispensedInventory VALUES(@psku, @psod, @pcod, @paxod, @padod, " +
@"@psos, @pcos, @paxos, @pados, @ptype, @pgen, @psize, @ptint, @padate, @pddate, @pcom)";
DBParams[0].Value = sprec.SKU;
DBParams[1].Value = sprec.SphereOD;
DBParams[2].Value = sprec.CylOD;
DBParams[3].Value = sprec.AxisOD;
DBParams[4].Value = sprec.AddOD;
DBParams[5].Value = sprec.SphereOS;
DBParams[6].Value = sprec.CylOS;
DBParams[7].Value = sprec.AxisOS;
DBParams[8].Value = sprec.AddOS;
DBParams[9].Value = sprec.Type;
DBParams[10].Value = sprec.Gender;
DBParams[11].Value = sprec.Size;
DBParams[12].Value = sprec.Tint;
DBParams[13].Value = sprec.DateAdded;
DBParams[14].Value = sprec.DateDispensed;
DBParams[15].Value = sprec.Comment;
try
{
DBcmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
//Delete the record from the CurrentInventory table
DBcmd.CommandText = @"DELETE FROM CurrentInventory WHERE SKU = @psku";
try
{
DBcmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
//Clean up the DataTables for display purposes - This does not affect the backend DB
if (ismain) //Main table cleanup
{
int dbrc = dbresults.Rows.Count;
for (int i = 0; i < dbrc; i++)
{
if (Convert.ToUInt16(dbresults.Rows[i][0]) == sprec.SKU)
{
dbresults.Rows.Remove(dbresults.Rows[i]);
break;
}
}
}
else //Auxiliary table cleanup (only happens for split multifocals)
{
int dbrc = tresults.Rows.Count;
for (int i = 0; i < dbrc; i++)
{
if (Convert.ToUInt16(tresults.Rows[i][0]) == sprec.SKU)
{
tresults.Rows.Remove(tresults.Rows[i]);
break;
}
}
}
}
/// <summary>
/// Permanently deletes a record from the database
/// </summary>
/// <remarks>NOT FOR DISPENSING</remarks>
/// <param name="sku">The SKU corresponding to the record to be deleted</param>
/// <exception cref="System.Exception">Thrown when the record could not be deleted</exception>
public void Delete(uint sku, SSTable _table)
{
if (_table == SSTable.MergeItems)
{
DBcmd.CommandText = @"DELETE FROM MergeItems WHERE SKU = @psku";
}
else
{
DBcmd.CommandText = @"DELETE FROM CurrentInventory WHERE SKU = @psku";
}
try
{
DBParams[0].Value = sku;
DBcmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// Merges the data from one SecondSight database into the currently open one
/// </summary>
/// <remarks>This merge is only performed on CurrentInventory. Any records with duplicate SKUs are ignored (ie. no overwriting)</remarks>
/// <param name="mergeDB">The SecondSight database to be merged into the current one</param>
/// <exception cref="System.Data.SQLite.SQLiteException">Thrown if any part of the merge fails</exception>
public void SmallMerge(SSDataBase mergeDB)
{
//Attach the merge database to the master
DBcmd.CommandText = "ATTACH '" + mergeDB.MyPath + "' AS TOMERGE";
DBcmd.ExecuteNonQuery();
using (SQLiteTransaction dbt = DBConn.BeginTransaction())
{
DBcmd.CommandText = "INSERT INTO CurrentInventory SELECT * FROM TOMERGE.CurrentInventory WHERE SKU NOT IN (SELECT SKU FROM CurrentInventory)";
try
{
DBcmd.ExecuteNonQuery();
}
catch (SQLiteException ex)
{
dbt.Rollback();
throw new Exception("Failed to merge.", ex.InnerException);
}
dbt.Commit();
}
//Detach the database
DBcmd.CommandText = "DETACH TOMERGE";
DBcmd.ExecuteNonQuery();
}
//Gets the full inventory and stores it in the invresults DataTable
//Used by the inventory display in the Add New Item and Full Inventory View tabs
public void GetCurrentInventory()
{
invresults.Clear();
SQLiteDataAdapter da;
using (SQLiteTransaction dbt = DBConn.BeginTransaction())
{
DBcmd.CommandText = @"SELECT * FROM CurrentInventory ORDER BY SKU";
da = new SQLiteDataAdapter(DBcmd);
try
{
da.Fill(invresults);
}
catch
{
invresults.Clear();
}
}
}
/// <summary>
/// Gets the full contents of a single table and stores it in a DataTable
/// </summary>
/// <param name="_dt">The DataTable to store the data in</param>
/// <param name="_table">Which table to read the data from</param>
/// <exception cref="System.Data.SQLite.SQLiteException">Thrown when the table is empty and the DataTable can't be filled</exception>
public void GetTable(DataTable _dt, SSTable _table)
{
SQLiteDataAdapter da;
string commandstring = "";
//Select the appropriate command string
switch (_table)
{
case SSTable.Current:
commandstring = @"SELECT * FROM CurrentInventory ORDER BY SKU";
break;
case SSTable.Dispensed:
commandstring = @"SELECT * FROM DispensedInventory ORDER BY SKU";
break;
case SSTable.DBInfo:
commandstring = @"SELECT * FROM DBInfo";
break;
case SSTable.MergeInfo:
commandstring = @"SELECT * FROM MergeInfo";
break;
case SSTable.MergeItems:
commandstring = @"SELECT * FROM MergeItems ORDER BY SKU";
break;
default:
break;
}
//Build and execute the transaction
using (SQLiteTransaction dbt = DBConn.BeginTransaction())
{
DBcmd.CommandText = commandstring;
da = new SQLiteDataAdapter(DBcmd);
try
{
da.Fill(_dt);
}
catch (Exception ex)
{
throw ex;
}
}
}
//Searches current inventory for certain SKUs and stores the results
//in the passed-in DataTable dt
public void SKUSearch(int sku, DataTable dt)
{
SQLiteDataAdapter da;
using (SQLiteTransaction dbt = DBConn.BeginTransaction())
{
DBcmd.CommandText = "SELECT * FROM CurrentInventory WHERE SKU = @psku";
da = new SQLiteDataAdapter(DBcmd);
DBParams[0].Value = sku;
try
{
da.Fill(dt);
}
catch (SQLiteException e)
{
if (e.ErrorCode == SQLiteErrorCode.IOErr)
{
throw new SQLiteException("IO Error", e.InnerException);
}
}
dbt.Commit();
}
}
//Query everything in the duplicates table and store results in dt
public void GetDuplicates(DataTable dt)
{
SQLiteDataAdapter da;
using (SQLiteTransaction dbt = DBConn.BeginTransaction())
{
DBcmd.CommandText = "SELECT * FROM DupedInventory ORDER BY SKU";
da = new SQLiteDataAdapter(DBcmd);
try
{
da.Fill(dt);
}
catch (SQLiteException e)
{
if (e.ErrorCode == SQLiteErrorCode.IOErr)
dt.Clear();
else
Console.WriteLine(e.Message);
}
}
}
//Query everything in the DBInfo table and store results in dt
public void GetDBInfo(DataTable dt)
{
SQLiteDataAdapter da;
using (SQLiteTransaction dbt = DBConn.BeginTransaction())
{
DBcmd.CommandText = "SELECT * FROM DBInfo";
da = new SQLiteDataAdapter(DBcmd);
try
{
da.Fill(dt);
}
catch (SQLiteException e)
{
if (e.ErrorCode == SQLiteErrorCode.IOErr)
dt.Clear();
}
}
}
/// <summary>
/// Retrieves the first unused SKU in CurrentInventory
/// </summary>
/// <returns>The first unused SKU</returns>
public int GetNextFreeSKU()
{
int numrecords = invresults.Rows.Count;
int currentsku = 1; //Current SKU to check, return value if it does not exist in database
int tsku; //Temporary int to hold converted SKU values from the database
if (numrecords > 0)
{
tsku = Convert.ToInt16(invresults.Rows[0][0]);
if (tsku > 1)
{
currentsku = 1;
}
else
{
currentsku = tsku;
}
}
for (int i = 0; i < numrecords; i++)
{
tsku = Convert.ToInt16(invresults.Rows[i][0]);
if (tsku != currentsku)
{
return currentsku;
}
currentsku++;
}
return currentsku;
}
/// <summary>
/// Retrieves the first unused SKU in CurrentInventory within a specified range
/// </summary>
/// <param name="smin">The minimum SKU to check</param>
/// <param name="smax">The maximum SKU to check</param>
/// <returns>The first unused SKU in the range</returns>
public int GetNextFreeSKU(int smin, int smax)
{
int numrecords = invresults.Rows.Count;
int currentsku = smin;
int imin = 0; //Index in the data table of the sku specified by smin
int currentindex = 0; //Current index
if (smin < 1)
{
smin = currentsku = 1;
}
//Find starting index
while (imin < numrecords && Convert.ToInt16(invresults.Rows[imin][0]) < smin)
{
imin++;
}
currentindex = imin;
//Find ending index
while (currentindex < numrecords && currentsku == Convert.ToInt16(invresults.Rows[currentindex][0]))
{
if (currentsku == smax)
{
throw new IndexOutOfRangeException("No free SKUs in range.");
}
currentsku++;
currentindex++;
}
return currentsku;
}
/// <summary>
/// Converts the currently open database into the newest format
/// </summary>
/// <remarks>The _cvtype parameter corrseponds to SecondSight database versions that need changing.
/// 0 = Version 0.90 </remarks>
/// <param name="_cvtype">Integer representation of the convertable database version</param>
private void DBConvert(int _cvtype)
{
DataTable tcitable = new DataTable(); //Temporary table to hold current inventory
DataTable tditable = new DataTable(); //Temporary table to hold dispensed inventory
DataTable tinfotable = new DataTable(); //Temporary table to hold DB info
if (_cvtype == 0)
{ //Convert from version 0.90
SQLiteDataAdapter da;
using (SQLiteTransaction dbt = DBConn.BeginTransaction())
{
DBcmd.CommandText = @"SELECT * FROM CurrentInventory ORDER BY SKU";
da = new SQLiteDataAdapter(DBcmd);
try
{
da.Fill(tcitable); //Store CurrentInventory in a temporary table for conversion
}
catch
{
tcitable.Clear();
}
da.Dispose();
DBcmd.CommandText = @"SELECT * FROM DispensedInventory ORDER BY SKU";
da = new SQLiteDataAdapter(DBcmd);
try
{
da.Fill(tditable); //Store DispensedInventory in a temporary table for conversion
}
catch
{
tditable.Clear();
}
da.Dispose();
DBcmd.CommandText = @"SELECT * FROM DBInfo";
da = new SQLiteDataAdapter(DBcmd);
try
{
da.Fill(tinfotable); //Store DB Info in a temporary table for conversion
}
catch
{
tinfotable.Clear();
}
}
//Alter the tables. Because SQLite only supports a limited subset of ALTER TABLE,
//this alteration is done by recreating the database file
DBConn.Close(); //Close the connection and delete the old database file
if (File.Exists(DBPath))
{
File.Delete(DBPath);
}
//Run the create new db function to recreate the database based on the info in the DBInfo table
CreateNewDB(DBPath, tinfotable.Rows[0][0].ToString(), tinfotable.Rows[0][1].ToString());
//Update the date created to the correct value
using (SQLiteTransaction dbt = DBConn.BeginTransaction())
{
DBcmd.CommandText = "UPDATE DBInfo SET DateCreated = @pdbdate";
DBParams[18].Value = String.Format("{0:yyyy-MM-dd}", tinfotable.Rows[0][2].ToString());
DBcmd.ExecuteNonQuery();
}
//Add the data back into the newly formatted tables
using (SQLiteTransaction dbt = DBConn.BeginTransaction())
{
DBcmd.CommandText = @"INSERT INTO CurrentInventory VALUES(@psku, @psod, @pcod, @paxod, @padod, " +
@"@psos, @pcos, @paxos, @pados, @ptype, @pgen, @psize, @ptint, @padate, @pcom)";
//Set up each parameter
foreach (DataRow row in tcitable.Rows)
{
DBParams[0].Value = row[0];
DBParams[1].Value = row[1];
DBParams[2].Value = row[2];
DBParams[3].Value = row[3];
DBParams[4].Value = row[4];
DBParams[5].Value = row[5];
DBParams[6].Value = row[6];
DBParams[7].Value = row[7];
DBParams[8].Value = row[8];
DBParams[9].Value = row[9];
DBParams[10].Value = row[10];
DBParams[11].Value = row[11];
DBParams[12].Value = row[12];
DBParams[13].Value = String.Format("{0:yyyy-MM-dd}", DateTime.Parse(row[13].ToString()));
DBParams[15].Value = row[14];
try
{
DBcmd.ExecuteNonQuery();
}