/
dbsql.cpp
3299 lines (2900 loc) · 92.4 KB
/
dbsql.cpp
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
/*
19980321 Mvh Changed ObjectFile and DeviceName field length to 250 for dbf compatibility
19980321 Mvh Added define TRUNCATEFIELDNAMES for DBF compatibity (apply in makefile)
19980322 Mvh Added run-time check on DbaseIII (should also be added in parse.cpp somehow)
19980325 Mvh Added TruncateFieldNames entry in dicom.ini to allow DBF compatibility
19980327 Mvh Made MaxFieldLength configurable
19980327 Mvh Set default event notification to UDP (for personal pacs)
19980407 Mvh Added FileCompressMode config
19980409 Mvh Check vr!=NULL in MakeSafeString,MakeSafeDate
19990630 MvH Remove also files from MIRROR disks
19990707 MvH Added UpdateOrAddToTable to refresh database contents without first removing
19990707 MvH Cache Updates; and AccessTime with ~31 to allow update times to be the same
19990707 MvH Added fix for Philips PATID; fix cleaning of MIRROR device
19990708 MvH Added (and disabled) stress code for SQL server
19990712 MvH Fixed FIX_PHILIPS; atoi failed sometimes because vr->data not zero termimated
19990827 MvH Added creation of key and link indices
19991117 ljz Added a check on ini-file value of FileCompressMode
20000221 ljz Changed layout of this update-history
Fix: In 'SetString', type DT_UINT32 was treated as DT_UINT16
Added TroubleLogFile and UserLogFile
When updating PaientRecord, verify the new Name and BirthDate
20000629 ljz Logging of trouble now starts with '***'
20000701 mvh Remove *all* trailing spaces im MakeSafeString before enters database
20000703 mvh Merged changes: made patient change verification table and record name
independent and extended to other databases as well; removed trailing
spaces before comparison; show patid on all error messages
20000705 mvh refuse inconsistent update of link: show error on operatorconsole
20000707 mvh fixed above addition
20001104 mvh Replaced _rmdir by equaly valid rmdir
20001106 mvh Use delete [] operation for vr->Data
20001128 ljz Fix: protected 'GetFileName' with a critical section.
20010415 mvh Added KeepImages flag to RemoveFromPacs: clear from DB only
20010416 mvh Added ChangeUID routine and UIDMODS table - to allow modification of images
20010418 mvh Changed names of database fields in UIDMODS - did not work on msaccess
20010429 mvh Renamed genuid routine and variables to allow compile in one big file
20010713 mvh Reduced devicename to 32 chars to space space
20010902 mvh Improved UpdateCache to be thread safe and made it longer, no test on image db
20011109 mvh Made MAG check and database field consistency check case insensitive
20011115 mvh Replaced 'LIKE' by faster '=' when possible
20011116 mvh Fixed error handling of db entry. It was possible that db entry
failed without any message!
20011121 mvh Create indices on ImagePat and SeriesPat if these fields exist
20020403 ljz Do not overrrule the PatientTable with: empty data, or birthdate xxxx0101,
or sex other than MmFf.
20020409 mvh made LastPatid non-static
20020409 mvh Removed non-thread safe caching of LastADBE
20020409 mvh Moved entry into UpdateCache to after succesful Update
20020412 mvh Made NCACHE configurable and changed it from 16 to 1024 (8 MB);
Set lastfield (limit of #fields) to 20 (was 16)
Added checksum code in update cache to make it faster
20020412 mvh Made key fields unique. reversed writing of db's. In this case
a db write fail will still result in a valid db
The db write code is not multi-user safe. A new record
may be written at the same time by two processes -> fail
20020413 mvh Set NCACHE to 256, enough for single thread regen
Modified another non-thread safe construct
20020415 mvh Fix display of PatientID in 'Inconsistent' error message
20020416 mvh Made UID generator configurable through UIDPrefix in dicom.ini
Made all instances of time unsigned
Note: accesstime in the db is signed int: problem around 2038
20020418 mvh+ljz Added TimeStamp, Flags, and Spare fields on all dbs for future use
20020430 mvh Fix in spare fields: name was reserved in some odbc implementations
20020515 mvh Process all db fields; enter (1) Modality into StudyModality
20020517 mvh Modality is merged into StudyModality without size limit (enforced by sql server)
20020518 mvh Skip missing VR's again; max nr fields to 30; fix reading of NULL fields (clear s[][])
20020519 mvh Also skip writing empty VR's (vr->Length==0); made FixPhilips configurable (default 1)
Remove / from date to allow writing mm/dd/yyyy into sql server
20020522 ljz Test on empty Modality vr
20020529 mvh Added PRIMARY KEY to key DB fields (needed for replication)
20020529 mvh InitializeTables now has mode parameter (0=normal, 1=simple);
Do not make Index for primary keys (is done automatically)
20020609 mvh Added compression modes 3 and 4
20020802 mvh Simplified rmdir code and allow multiple subdirectories
20020804 mvh Use PATHSEPCHAR where possible
20020806 mvh Fix: cleanup entries of refused item in database
20020819 mvh Added better UID generation
20021016 mvh Use patid in SaveToDatabase and GetFileName query
(both test for rev5 or higher of the database)
20021017 mvh Allow set of UIDpostfix from extern (-c option of dgate)
Removed creation of unused tables
20021020 mvh Added [ to MakeSafeString; removed "
Note: VR's containing ', ? give spurious inconsistency warning when rewritten
20021028 mvh Also removed dropping of unused tables; reversed table search to image..pat in FindDBE
Made inconsistent birtdate a severe error message (added ***)
20021110 mvh Made date range inclusive (bug reported by Aaron Cann)
20030113 mvh Added PatientQuerySortOrder etc overrides for sorting
20030205 mvh Fix potential empty patient ID and SOP problems in GetFilename
20030321 ljz Extra check on vr!=NULL in SaveToDatabase
20031104 mvh Added \\ to MakeSafeString
20040301 ljz Do not double \\ when allready doubled
20030425 mvh Added DoubleBackSlashToDB control for \\
20040528 mvh Pass patient ID in RemoveFromPacs and Enable KeyOnAll
20040529 mvh Implemented faster delete from database
20040530 mvh Pass a field to query in delete - obligatory for sql server
20040601 mvh Removed enable KeyOnAll - added some more checks in NewDeleteFromDB
20040609 mvh Check for DB revision for fast delete from database queries
20040610 mvh Truncate too long VR's before putting into db; log to pacstrouble
20040623 ljz Fix for non-DBASE datasources in 'UpdateOrAddToTable':
20040626 mvh Added study and series UID to getfilename interface
20040713 mvh Added FixKodak: replaces patid 0NNNNNNN with NNNNNNNN
20040722 mvh Defaults for FixKodak and FixPhilips to 0 (!)
20040930 mvh Added multiple UID matching: UID\UID\UID in BuildSearchString (list truncates at maximum length)
SetString now returns a char * which is newed (with lots of extra space
for MakeSafeString which is done in-place) if Max length is passed 0
DICOM2SQLQuery has no max length anymore
20041003 mvh Trucated printfs of SqlStatement
20041029 mvh Added MergeUIDs routine
20041101 mvh Added NewDeleteSopFromDB
20041220 ljz Fix: in 'RemoveFromPACS', an even PatientID was not zero-terminated !!
20050109 mvh Adapted for linux compile
20050111 mvh Added ctype.h (for mingw)
20050205 mvh Added counters for database activity
20050206 mvh Allow empty DBE in ConstructVRFromSQL: used to get ObjectFile and Device in query
20050401 mvh Added WorkListDB and WorkListTableName
20050404 mvh Dicom types DT_START/ENDSEQUENCE are ignored during table creation/adding to table
20050414 mvh Allow undefined worklist database;
Delete patient will delete worklist entries as well (but needs at least one image)
20050417 mvh Delete from DB will also delete worklist as patient goes
20050826 mvh Added mode 2 for initializetables: clear/create worklist only
20050831 mvh Mode 0 and 1 will now not delete worklist if it contains data
20050831 mvh VerifyIsInDBE will not return DT_START/ENDSEQUENCE
20050901 mvh Do not call FixImage in SaveToDataBase: is done in SaveToDisk before
20051121 mvh Enabled SQLRealSize because SQLResultLength does not work in PostGres BindField
20051123 mvh Fixed it, and only enable it when #ifdef POSTGRES
20051204 mvh Disabled it, fixed postgres driver instead
20051210 mvh GetFilename returns FALSE for an image that has no filename or device set
20051212 mvh Clear update cache when any records deleted - drastic but safe
20051216 mvh Small fix in above
20051217 mvh Use new VR::ReAlloc method to replace data in VR
20051218 mvh Fix study modality when DoubleBackSlashToDB=1; changed modality search
20051228 mvh Truncate invalid trailing spaces (>1) from patient ID.
20051228 mvh Fiximage warns to SystemDebug; Renamed DebugVRs to DebugLevel
20060210 mvh Removed order: first remove spaces and then fix the patient ID
because patient ID consisting of 14 spaces caused huge troubles
20060220 mvh Check max 50 fields when update; fix Inconsistent check for DoubleBackSlashToDB
20060607 mvh Fix character translation for entering *?%[' into sql using MakeSafeStringValues
Fix consistency check for these characters as well (thanks Robert Chrzan)
20060607 mvh Added "not null" to "PRIMARY KEY" to satisfy Sybase (thanks Marcin Litoborski)
20060618 mvh Added not null to UIDmods as well, unified case of DICOMWorkList table name
(may be done for other tables as well)(thanks Marcin Litoborski)
20060618 mvh Remove '' added by MakeSafeStringValues prior to inconsistency check (thanks Robert Chrzan)
20060621 mvh Increased size of s from [50][255] to [51][256] in UpdateOrAddToTable fixes VirtualQuery crash
20060628 mvh AddToDatabase has JustAdd parameter: skip one unnecessary query
20060706 mvh Replaced faulty new vr construct when doing consistency check: faulted on Linux
20061213 mvh Protect Clear_UpdateCache with critical section
Fixed nasty bug in NewDeleteFromDB. MergeUIDs, NewDeleteSopFromDB: Query without bindfield overwrites previous bound strings!
20070123 mvh Fixed GetFileName for patientid with '
Recoded some of the inconsistency checking: now no failure on patient ID (link) with '
20070131 mvh Fixed GetFileName for all patientid's ;->>>>
20070201 mvh Fixed (unused) UpdateAccessTimes for weird patient IDs
20070210 mvh Added CheckDuplicates to UpdateOrAddToTable: used on DicomStudies to catch inconsistent patientID
Enabled KeyOnAll on UpdateOrAddToTable: only delete exact records (needed if inconsistent patientID)
20070308 bcb Changed to set patient ID to 0 for anonymized patients
20070315 mvh Merged; also noted that changed possible use of AND at start of sql where
20071027 mvh Also truncate too long date fields with error message; added AllowTruncate: if sql name
in comma separated list: warning only else ***error
20071118 mvh Adapted for 64 bits (use SQLLEN for BindField)
20080302 mvh Fixed case of DICOM table names
20080319 mvh Fixed typo in above change; fixed worklist delete for patients with space in ID
20080817 mvh Added WorkListReturnsISO_IR_100 flag (default 1)
20080818 mvh DbaseIII check now uses DB flags, not PATHSEP in datasource name
Added experimental DT_MSTR: multi-value entry, e.g. query on 'PET' matches 'PET\CT'
if studymodality is given type DT_MSTR instead of DT_STR. Note: not implemented for DBASEIII
20080819 mvh Added warning when querying DT_MSTR field on dbase
20080902 mvh added EnableComputedFields (default 0)
*/
#define NCACHE 256
#ifndef WHEDGE
# include "dgate.hpp"
#else
# include "master.h"
#endif
#ifndef UNIX
# include <direct.h>
#else
#include <unistd.h>
#include <ctype.h>
#include "gpps.hpp"
#define stricmp(s1, s2) strcasecmp(s1, s2)
#define EnterCriticalSection(a) pthread_mutex_lock(a)
#define LeaveCriticalSection(a) pthread_mutex_unlock(a)
#define CRITICAL_SECTION pthread_mutex_t
#define InitializeCriticalSection(a) pthread_mutex_init(a, NULL);
#define DeleteCriticalSection(a) pthread_mutex_destroy(a);
#endif
# include <time.h>
# include <stdlib.h>
# include <ctype.h>
DBENTRY *PatientDB = NULL, *StudyDB = NULL, *SeriesDB = NULL, *ImageDB = NULL, *WorkListDB = NULL;
DBENTRY *LastADBE = NULL;
UINT DebugVRs = 0;
UINT Edition = E_WORKGROUP;
char EditionText[128] = "Workgroup";
char DataHost[128] = "localhost";
char DataSource[128] = "LABRAD2";
char UserName[128] = "Administrator";
char Password[128] = "password";
char PatientTableName [64] = "DICOMPatients";
char StudyTableName [64] = "DICOMStudies";
char SeriesTableName [64] = "DICOMSeries";
char ImageTableName [64] = "DICOMImages";
char WorkListTableName [64] = "DICOMWorkList";
char DMarkTableName [64] = "DICOMAccessUpdates";
char RegisteredMOPIDTableName [64] = "RegisteredMOPIDs";
char UIDToMOPIDTableName [ 64 ] = "UIDToMOPID";
char UIDToCDRIDTableName [ 64 ] = "UIDToCDRID";
BYTE Port [ 64 ];
BYTE KFACTORFILE [ 256 ] = "dicom.sql";
BYTE MYACRNEMA [ 64 ] = "none";
char SOPClassFile [ 128 ] = "dgatecls.lst";
#ifndef UNIX
char OCPipeName[256] = "\\\\.\\pipe\\MicroPACSStatus";
char ACPipeName[256] = "\\\\.\\pipe\\MicroPACSAccess";
#else
char OCPipeName[256] = "/tmp/MicroPACSStatus";
char ACPipeName[256] = "/tmp/MicroPACSAccess";
#endif
char ServerName[256] = "Marks Machine";
char UserLogFile[256] = "PacsUser.log";
char TroubleLogFile[256] = "PacsTrouble.log";
int SkippedCachedUpdates=0;
int UpdateDatabase=0;
int AddedDatabase=0;
# define DEBUG_MODE
#ifndef RootConfig
extern char RootConfig[];
#endif
#ifndef ConfigFile
extern char ConfigFile[];
#endif
static int TruncateFieldNames=0;
static int MaxFieldLength=0;
static int FixPhilips=0;
static int FixKodak=0;
static int DoubleBackSlashToDB=0;
int FileCompressMode=0;
char PatientQuerySortOrder[256]="";
char StudyQuerySortOrder[256]="";
char SeriesQuerySortOrder[256]="";
char ImageQuerySortOrder[256]="";
char AllowTruncate[256]="";
int WorkListReturnsISO_IR_100=0;
int EnableComputedFields=0;
// Forward declaration
BOOL
UpdateOrAddToTable(
Database &DB,
DBENTRY *DCMGateDB,
char *TableName,
DICOMDataObject *DDOPtr,
char *ObjectFile,
char *DeviceName,
char *Patid,
char *Modality,
BOOL *Added,
BOOL JustAdd,
BOOL CheckDuplicates);
static
void
ConfigDBSpecials(void)
{
char RootSC[64];
char Temp[128];
GetPrivateProfileString ( RootConfig, "MicroPACS", RootConfig,
(char*) RootSC, 64, ConfigFile);
GetPrivateProfileString ( RootSC, "TruncateFieldNames", "0",
(char*) Temp, 128, ConfigFile);
TruncateFieldNames = atoi(Temp);
GetPrivateProfileString ( RootSC, "MaxFieldLength", "0",
(char*) Temp, 128, ConfigFile);
MaxFieldLength = atoi(Temp);
GetPrivateProfileString ( RootSC, "DoubleBackSlashToDB", "0",
(char*) Temp, 128, ConfigFile);
DoubleBackSlashToDB = atoi(Temp);
GetPrivateProfileString ( RootSC, "FixPhilips", "0",
(char*) Temp, 128, ConfigFile);
FixPhilips = atoi(Temp);
GetPrivateProfileString ( RootSC, "FixKodak", "0",
(char*) Temp, 128, ConfigFile);
FixKodak = atoi(Temp);
GetPrivateProfileString ( RootSC, "WorkListReturnsISO_IR_100", "1",
(char*) Temp, 128, ConfigFile);
WorkListReturnsISO_IR_100 = atoi(Temp);
GetPrivateProfileString ( RootSC, "EnableComputedFields", "0",
(char*) Temp, 128, ConfigFile);
EnableComputedFields = atoi(Temp);
GetPrivateProfileString ( RootSC, "FileCompressMode", "0",
(char*) Temp, 128, ConfigFile);
FileCompressMode = atoi(Temp);
if ((FileCompressMode < 0) || (FileCompressMode > 4))
FileCompressMode = 0;
GetPrivateProfileString ( RootSC, "PatientQuerySortOrder", "",
(char*) PatientQuerySortOrder, 256, ConfigFile);
GetPrivateProfileString ( RootSC, "SeriesQuerySortOrder", "",
(char*) SeriesQuerySortOrder, 256, ConfigFile);
GetPrivateProfileString ( RootSC, "StudyQuerySortOrder", "",
(char*) StudyQuerySortOrder, 256, ConfigFile);
GetPrivateProfileString ( RootSC, "ImageQuerySortOrder", "",
(char*) ImageQuerySortOrder, 256, ConfigFile);
GetPrivateProfileString ( RootSC, "AllowTruncate", "",
(char*) AllowTruncate, 256, ConfigFile);
strcat(AllowTruncate, ",");
}
BOOL
ConfigDebug (
char *ConfigSection,
char *ConfigFile,
char *Prefix,
Debug *Dbg )
{
char ConfigString[128];
char Temp[128];
char Temp2[128];
strcpy(ConfigString, Prefix);
strcat(ConfigString, ".TransportType");
GetPrivateProfileString ( ConfigSection, ConfigString,
"UDP",
(char*) Temp, 64, ConfigFile);
if ( ! stricmp ( Temp, "File" ) )
{
strcpy(ConfigString, Prefix);
strcat(ConfigString, ".FileName");
GetPrivateProfileString ( ConfigSection, ConfigString,
"nofile.log",
(char*) Temp, 64, ConfigFile);
Dbg->On(Temp);
return ( TRUE );
}
else
if ( ! stricmp ( Temp, "NamedPipe") )
{
strcpy(ConfigString, Prefix);
strcat(ConfigString, ".NamedPipeName");
GetPrivateProfileString ( ConfigSection, ConfigString,
"\\\\.\\pipe\\nopipe",
(char*) Temp, 64, ConfigFile);
Dbg->OnMsgPipe(Temp);
return ( TRUE );
}
else
if ( ! stricmp ( Temp, "UDP" ) )
{
strcpy(ConfigString, Prefix);
strcat(ConfigString, ".UDPHost");
GetPrivateProfileString ( ConfigSection, ConfigString,
"localhost",
(char*) Temp, 64, ConfigFile);
strcpy(ConfigString, Prefix);
strcat(ConfigString, ".UDPPort");
GetPrivateProfileString ( ConfigSection, ConfigString,
"1111",
(char*) Temp2, 64, ConfigFile);
Dbg->OnUDP(Temp, Temp2);
return ( TRUE );
}
return ( FALSE );
}
/*
BOOL
ConfigEventNotification (
char *ConfigSection,
char *ConfigFile )
{
ConfigDebug ( ConfigSection, ConfigFile, "MajorEvent", &MajorEvent );
ConfigDebug ( ConfigSection, ConfigFile, "MinorEvent", &MinorEvent );
return ( TRUE );
}
*/
BOOL ConfigMicroPACS()
{
char RootSC[64];
char Temp[128];
GetPrivateProfileString ( RootConfig, "MicroPACS", RootConfig,
(char*) RootSC, 64, ConfigFile);
GetPrivateProfileString ( RootSC, "Edition", "Workgroup",
(char*) EditionText, 64, ConfigFile);
if ( !stricmp(EditionText, "Workgroup"))
Edition = E_WORKGROUP;
else
if ( !stricmp(EditionText, "Personal"))
Edition = E_PERSONAL;
else
if ( !stricmp(EditionText, "Enterprise"))
Edition = E_ENTERPRISE;
else
Edition = E_WORKGROUP;
GetPrivateProfileString ( RootSC, "TCPPort", "104",
(char*) Port, 64, ConfigFile);
GetPrivateProfileString ( RootSC, "DebugLevel", "0",
(char*) Temp, 64, ConfigFile);DebugVRs = atoi(Temp);
GetPrivateProfileString ( RootSC, "kFactorFile", "dicom.sql",
(char*) KFACTORFILE, 64, ConfigFile);
GetPrivateProfileString ( RootSC, "ACRNemaMap", "acrnema.map",
(char*) ACRNEMAMAP, 64, ConfigFile);
GetPrivateProfileString ( RootSC, "MyACRNema", "none",
(char*) MYACRNEMA, 64, ConfigFile);
GetPrivateProfileString ( RootSC, "SOPClassList", "dgatesop.lst",
(char*) SOPClassFile, 128, ConfigFile);
// SQL server network hostname
GetPrivateProfileString ( RootSC, "SQLHost", "localhost",
(char*) DataHost, 128, ConfigFile);
if(strlen(DataHost) == 0)
{
strcpy(DataHost, "localhost");
}
GetPrivateProfileString ( RootSC, "SQLServer", "LABRAD2",
(char*) DataSource, 128, ConfigFile);
GetPrivateProfileString ( RootSC, "Username", "Administrator",
(char*) UserName, 128, ConfigFile);
GetPrivateProfileString ( RootSC, "Password", "password",
(char*) Password, 128, ConfigFile);
GetPrivateProfileString ( RootSC, "PatientTableName", "DICOMPatients",
(char*) PatientTableName, 64, ConfigFile);
GetPrivateProfileString ( RootSC, "WorkListTableName", "DICOMWorkList",
(char*) WorkListTableName, 64, ConfigFile);
GetPrivateProfileString ( RootSC, "StudyTableName", "DICOMStudies",
(char*) StudyTableName, 64, ConfigFile);
GetPrivateProfileString ( RootSC, "SeriesTableName", "DICOMSeries",
(char*) SeriesTableName, 64, ConfigFile);
GetPrivateProfileString ( RootSC, "ImageTableName", "DICOMImages",
(char*) ImageTableName, 64, ConfigFile);
GetPrivateProfileString ( RootSC, "DMarkTableName", "DICOMAccessUpdates",
(char*) DMarkTableName, 64, ConfigFile);
GetPrivateProfileString ( RootSC, "RegisteredMOPIDTableName", "RegisteredMOPIDs",
(char*) RegisteredMOPIDTableName, 64, ConfigFile);
GetPrivateProfileString ( RootSC, "UIDToMOPIDTableName", "UIDToMOPID",
(char*) UIDToMOPIDTableName, 64, ConfigFile);
GetPrivateProfileString ( RootSC, "UIDToCDRIDTableName", "UIDToCDRID",
(char*) UIDToCDRIDTableName, 64, ConfigFile);
GetPrivateProfileString ( RootSC, "OperatorConsole",
"\\\\.\\pipe\\MicroPACSStatus", (char*)OCPipeName, 128, ConfigFile);
GetPrivateProfileString ( RootSC, "AccessUpdates",
"\\\\.\\pipe\\MicroPACSAccess", (char*)ACPipeName, 128, ConfigFile);
GetPrivateProfileString ( RootSC, "PACSName", "MicroPACS",
(char*) ServerName, 128, ConfigFile);
GetPrivateProfileString ( RootSC, "UserLog", "PacsUser.log",
(char*) UserLogFile, 128, ConfigFile);
GetPrivateProfileString ( RootSC, "TroubleLog", "PacsTrouble.log",
(char*) TroubleLogFile, 128, ConfigFile);
// ConfigEventNotification ( RootSC, ConfigFile );
ConfigDBSpecials();
InitializeDeviceTable (RootSC);
return ( TRUE );
}
DWORD
CurrentTime()
{
return((DWORD)time(NULL) & (~31));
}
char *
UniqueKey(
DBENTRY *DBE)
{
if(!DBE)
return ("null");
return ( DBE[0].SQLColumn );
}
char *
UniqueLink(
DBENTRY *DBE)
{
if(!DBE)
return( "null");
return( DBE[LastDBE(DBE)].SQLColumn );
}
BOOL
AddStudyInstanceUID (DICOMDataObject *DDOPtr)
{
VR *vr;
// Search for the UID elsewere
vr = DDOPtr->GetVR(0x0021, 0x1070);
if(vr)
{
VR *vrNew = new VR(0x0020, 0x000d, vr->Length, TRUE);
memcpy(vrNew->Data, vr->Data, vr->Length);
DDOPtr->Push(vrNew);
return ( TRUE );
}
// not sure what to do.
VR *vrNew = new VR(0x0020, 0x000d, 10, TRUE);
strcpy((char*)vrNew->Data, "undefined");
DDOPtr->Push(vrNew);
return ( TRUE );
}
BOOL
AddSeriesInstanceUID (DICOMDataObject *DDOPtr)
{
VR *vr;
// Search for the UID elsewere
vr = DDOPtr->GetVR(0x0021, 0x1071);
if(vr)
{
VR *vrNew = new VR(0x0020, 0x000e, vr->Length, TRUE);
memcpy(vrNew->Data, vr->Data, vr->Length);
DDOPtr->Push(vrNew);
return ( TRUE );
}
// not sure what to do.
VR *vrNew = new VR(0x0020, 0x000e, 10, TRUE);
strcpy((char*)vrNew->Data, "undefined");
DDOPtr->Push(vrNew);
return ( TRUE );
}
// Fix possible problems in an image.
BOOL
FixImage(DICOMDataObject *DDOPtr)
{
// This routine fixes some deficient images (sent from outdated
// modalities).
VR *vr;
int i, count;
vr = DDOPtr->GetVR(0x0010, 0x0010);
if(!vr)
{
vr = new VR(0x0010, 0x0010, 8, (BOOL)TRUE);
memcpy(vr->Data, (void*)"NO NAME", 8);
DDOPtr->Push(vr);
SystemDebug.printf("Fiximage: Added patient name\n");
}
// truncate invalid trailing spaces (more than one) from patient ID
vr = DDOPtr->GetVR(0x0010, 0x0020);
if(vr)
{
count=0;
for (i=vr->Length-1; i>=0; i--)
if (((char*)(vr->Data))[i]==' ') count++; else break;
if (count > 0)
{
vr->Length -= count;
if (vr->Length&1) vr->Length++, count--;
if (count) SystemDebug.printf("Fiximage: truncated %d trailing spaces from patient ID\n", count);
}
}
if(!vr)
{
vr = new VR(0x0010, 0x0020, 8, (BOOL)TRUE);
memcpy(vr->Data, (void*)"00000000", 8);
DDOPtr->Push(vr);
SystemDebug.printf("Fiximage: Added patient ID\n");
}
else if (vr->Length < 2)
{
int Length;
char *s;
s = (char*)vr->Data;
Length = vr->Length;
while ( Length )
{
if (s[Length] == ' ')
{
--Length;
continue;
}
if (s[Length] == '\0')
{
--Length;
continue;
}
break;
}
vr->Length = Length;
if ( vr->Length < 2)
{
vr->ReAlloc(8);
memcpy(vr->Data, (void*)"00000000", 8);
}
SystemDebug.printf("Fiximage: Fixed empty patient ID\n");
}
else if (vr->Length==10 && vr->Data && FixPhilips)
{
char patid[11];
int Length;
memcpy(patid, (char *)(vr->Data), 10);
patid[10]=0;
if ( patid[0] == '0' && patid[1] == '0' && atoi(patid)>1000000 )
{
memset(patid, 0, 10);
if (((char *)(vr->Data))[2]=='0') memcpy(patid, ((char *)(vr->Data)) + 3, Length=7);
else if (((char *)(vr->Data))[1]=='0') memcpy(patid, ((char *)(vr->Data)) + 2, Length=8);
else if (((char *)(vr->Data))[0]=='0') memcpy(patid, ((char *)(vr->Data)) + 1, Length=9);
else memcpy(patid, (char *)(vr->Data) + 0, Length=10);
if (Length&1) Length++;
vr->ReAlloc(Length);
memcpy(vr->Data, patid, Length);
SystemDebug.printf("Fiximage: Fixed Philips patient ID\n");
}
}
else if (vr->Length==8 && vr->Data && FixKodak)
{
char patid[11];
int Length;
memcpy(patid, (char *)(vr->Data), 8);
patid[8]=0;
if ( patid[0] == '0' && atoi(patid)>1000000 )
{
memset(patid, 0, 10);
if (((char *)(vr->Data))[0]=='0') memcpy(patid, ((char *)(vr->Data)) + 1, Length=7);
else memcpy(patid, (char *)(vr->Data) + 0, Length=8);
if (Length&1) Length++;
vr->ReAlloc(Length);
memcpy(vr->Data, patid, Length);
SystemDebug.printf("Fiximage: Fixed Kodak patient ID\n");
}
}
vr = DDOPtr->GetVR(0x0020, 0x000d);
if(!vr)
AddStudyInstanceUID ( DDOPtr );
vr = DDOPtr->GetVR(0x0020, 0x000e);
if(!vr)
AddSeriesInstanceUID ( DDOPtr );
return ( TRUE );
}
/////////////////////////////////////////////////////////////////
/* This code forms a cache that saves the last NCACHE entries */
/* If the entry already exists, db writing can be skipped */
/////////////////////////////////////////////////////////////////
char UpdateCache[NCACHE][8192];
int UpdateCheckSums[NCACHE];
CRITICAL_SECTION UpdateCritical;
int UpdateTop=0, UpdateBottom=0;
int into_UpdateCache(char *in)
{
int i, sum, r;
char *p = in;
sum = 0;
while(*p) sum+=*p++;
if (UpdateTop==0 && UpdateBottom==0)
InitializeCriticalSection(&UpdateCritical);
EnterCriticalSection(&UpdateCritical);
/* clear cache if it is empty */
if (UpdateTop==0 && UpdateBottom==0)
for (i=0; i<NCACHE; i++)
UpdateCache[i][0]=0;
if ((UpdateTop+1)%NCACHE == UpdateBottom)
UpdateBottom = (UpdateBottom+1)%NCACHE; // delete oldest entry
strcpy(UpdateCache[UpdateTop], in);
UpdateCheckSums[UpdateTop] = sum;
r = UpdateTop;
UpdateTop = (UpdateTop+1)%NCACHE;
LeaveCriticalSection(&UpdateCritical);
return r;
}
int isin_UpdateCache(char *in)
{
int i, sum;
char *p = in;
if (UpdateTop==0 && UpdateBottom==0) return 0;
sum = 0;
while(*p) sum+=*p++;
EnterCriticalSection(&UpdateCritical);
for (i=UpdateTop; i!=UpdateBottom; i=(i==0 ? NCACHE-1 : i-1))
{
if (UpdateCheckSums[i] == sum)
if (strcmp(UpdateCache[i], in)==0)
{
LeaveCriticalSection(&UpdateCritical);
return 1;
}
}
LeaveCriticalSection(&UpdateCritical);
return 0;
}
// clear entire cache
void clear_UpdateCache(void)
{
if (UpdateTop==0 && UpdateBottom==0) return;
EnterCriticalSection(&UpdateCritical);
for (int i=0; i<NCACHE; i++)
{
UpdateCache[i][0]=0;
UpdateCheckSums[i] = -1;
}
LeaveCriticalSection(&UpdateCritical);
}
BOOL
SaveToDataBase(
Database &DB,
DICOMDataObject *DDOPtr,
char *filename,
char *device,
BOOL JustAdd)
{
char LastPatid[65], Modality[17];
char s1[128];
BOOL AddedImage, AddedStudy, AddedSeries, AddedPatient;
VR *vr;
memset(LastPatid, 0, 65);
vr = DDOPtr->GetVR(0x0010, 0x0020);
//Note: Some Anonymized patients have no Patient ID.
//The DICOMPatients table requires an ID, So set it to 0.
if(!vr)
{
vr = new VR;
vr->Group = 0x0010;
vr->Element = 0x0020;
vr->Length = 2;
vr->ReAlloc(vr->Length);
if ( !vr->Data ) return ( FALSE ); // memory error
memcpy(vr->Data,"0 ", vr->Length);
DDOPtr->Push(vr);
}
memcpy(LastPatid, vr->Data, vr->Length);
if (vr && vr->Length)
if (LastPatid[vr->Length-1]==' ') LastPatid[vr->Length-1]=0;
memset(Modality, 0, 17);
vr = DDOPtr->GetVR(0x0008, 0x0060);
if(vr)
{
memcpy(Modality, vr->Data, vr->Length);
if (vr->Length)
if (Modality[vr->Length-1]==' ')
Modality[vr->Length-1] = 0;
}
// Modality[2] = 0; // option to truncate all RT item to save StudyModality space
// FixImage(DDOPtr);
VR *SOPInstance = DDOPtr->GetVR(0x0008, 0x0018);
MakeSafeString(SOPInstance, s1);
AccessUpdate.printf("%s", s1);
// RemoveDuplicates(DB, PatientDB, PatientTableName, DDOPtr, FALSE);
// AddToTable(DB, PatientDB, PatientTableName, DDOPtr, NULL, NULL);
// RemoveDuplicates(DB, StudyDB, StudyTableName, DDOPtr, FALSE);
// AddToTable(DB, StudyDB, StudyTableName, DDOPtr, NULL, NULL);
// RemoveDuplicates(DB, SeriesDB, SeriesTableName, DDOPtr, FALSE);
// AddToTable(DB, SeriesDB, SeriesTableName, DDOPtr, NULL, NULL);
// RemoveDuplicates(DB, ImageDB, ImageTableName, DDOPtr, FALSE);
// AddToTable(DB, ImageDB, ImageTableName, DDOPtr, filename, device);
if (!UpdateOrAddToTable(DB, ImageDB, ImageTableName, DDOPtr, filename, device, LastPatid, NULL, &AddedImage, JustAdd, FALSE))
return FALSE;
if (!UpdateOrAddToTable(DB, SeriesDB, SeriesTableName, DDOPtr, filename, NULL, LastPatid, NULL, &AddedSeries, FALSE, FALSE))
{
if (AddedImage) RemoveDuplicates(DB, ImageDB, ImageTableName, DDOPtr, TRUE);
return FALSE;
}
// check for conflicting patid -------V */
if (!UpdateOrAddToTable(DB, StudyDB, StudyTableName, DDOPtr, filename, NULL, LastPatid, Modality, &AddedStudy, FALSE, TRUE))
{
if (AddedSeries) RemoveDuplicates(DB, SeriesDB, SeriesTableName, DDOPtr, TRUE);
if (AddedImage) RemoveDuplicates(DB, ImageDB, ImageTableName, DDOPtr, TRUE);
return FALSE;
}
if (!UpdateOrAddToTable(DB, PatientDB, PatientTableName, DDOPtr, filename, NULL, LastPatid, NULL, &AddedPatient, FALSE, FALSE))
{
if (AddedStudy) RemoveDuplicates(DB, StudyDB, StudyTableName, DDOPtr, TRUE);
if (AddedSeries) RemoveDuplicates(DB, SeriesDB, SeriesTableName, DDOPtr, TRUE);
if (AddedImage) RemoveDuplicates(DB, ImageDB, ImageTableName, DDOPtr, TRUE);
return FALSE;
}
return ( TRUE );
}
char *
SetString(VR *vr, char *s, int Max)
{
int Index;
UINT16 *tuint16;
UINT32 *tuint32;
DBENTRY *DBE;
// when Max = 0 passed: alloc automatically at right size; pointer returned
if (Max==0)
{
if (vr) Max = 2 * vr->Length + 3; else Max = 255; // must allow MakeSafeString in-place (!)
if (Max < 255) Max = 255;
s = new char[Max];
}
memset((void*)s, 0, Max);
if(vr)
if(vr->Data)
{
DBE = FindDBE(vr);
if(!DBE)
{
memcpy((void*)s, vr->Data, vr->Length%Max);
return ( s );
}
switch(DBE->DICOMType)
{
case DT_UI:
case DT_STR:
case DT_MSTR:
case DT_DATE:
memcpy((void*)s, vr->Data, vr->Length%Max);
Index = strlen(s);
if(Index)
{
if(s[Index-1]==' ')
{
s[Index-1]='\0';
}
}
return ( s );
case DT_UINT16:
tuint16 = (UINT16*)vr->Data;
sprintf(s, "%d", (*tuint16));
return ( s );
case DT_UINT32:
// tuint16 = (UINT16*)vr->Data;
// sprintf(s, "%d", (*tuint16));
tuint32 = (UINT32*)vr->Data;
sprintf(s, "%d", (*tuint32));
return ( s );
default:
memcpy((void*)s, vr->Data, vr->Length%Max);
return ( s );
}
}
return ( s );
}
BOOL MakeSafeStringValues (VR *vr, char *string);
BOOL
AddToTable(
Database &DB,
DBENTRY *DCMGateDB,
char *TableName,
DICOMDataObject *DDOPtr,
char *ObjectFile,
char *DeviceName)
{
UINT Index, CIndex;
Array < VR * > VRArray;
VR *vr;
VR FakeVR;
char Columns [ 4096 ];
char Values [ 4096 ];
char TempString [ 512 ];
Index = 0;CIndex = 0;
Columns [ 0 ] = '\0';
while ( TRUE )
{
if( ! DCMGateDB[Index] . Element )
break;
if (DCMGateDB[Index].DICOMType==DT_STARTSEQUENCE || DCMGateDB[Index].DICOMType==DT_ENDSEQUENCE)
vr = NULL;
else
vr = DDOPtr->GetVR( DCMGateDB [ Index ] . Group,
DCMGateDB [ Index ] . Element );
LastADBE = &DCMGateDB[Index];
VRArray.Add(vr);
if(vr)
{
if(CIndex)
strcat(Columns, ", ");
strcat(Columns, DCMGateDB [ Index ] . SQLColumn);
++CIndex;
}
++Index;
}
strcat( Columns, ", AccessTime" );
if(ObjectFile)
strcat ( Columns, ", ObjectFile" );
if(DeviceName)
strcat ( Columns, ", DeviceName" );
Index = 0;CIndex = 0;
Values [ 0 ] = '\0';
while ( Index < VRArray.GetSize() )
{
if ( (vr = VRArray.Get ( Index ) ) )
{
if(CIndex)
strcat ( Values, ", ");
LastADBE = &DCMGateDB[Index];
switch(DCMGateDB[Index].SQLType)
{
case SQL_C_CHAR:
MakeSafeStringValues ( vr, TempString );