-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathDatabase.cs
1088 lines (945 loc) · 43.5 KB
/
Database.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
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
/*
DSA Lims - Laboratory Information Management System
Copyright (C) 2018 Norwegian Radiation Protection Authority
This program 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.
This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*/
// Authors: Dag Robole,
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Linq;
namespace DSA_lims
{
public static class DB
{
private static List<Guid> LockedSamples = new List<Guid>();
private static List<Guid> LockedOrders = new List<Guid>();
public static string ConnectionString { get { return Properties.Settings.Default.dsa_limsConnectionString; } }
public static SqlConnection OpenConnection()
{
SqlConnection connection = new SqlConnection(ConnectionString);
connection.Open();
return connection;
}
public static DataTable GetDataTable(SqlConnection conn, SqlTransaction trans, string query, CommandType queryType, params SqlParameter[] parameters)
{
SqlDataAdapter adapter = new SqlDataAdapter(query, conn);
adapter.SelectCommand.CommandType = queryType;
adapter.SelectCommand.Transaction = trans;
adapter.SelectCommand.Parameters.AddRange(parameters);
DataTable dt = new DataTable();
adapter.Fill(dt);
return dt;
}
public static SqlDataReader GetDataReader(SqlConnection conn, SqlTransaction trans, string query, CommandType queryType, params SqlParameter[] parameters)
{
SqlCommand cmd = new SqlCommand(query, conn, trans);
cmd.CommandType = queryType;
cmd.Parameters.AddRange(parameters);
return cmd.ExecuteReader();
}
public static object GetScalar(SqlConnection conn, SqlTransaction trans, string query, CommandType queryType, params SqlParameter[] parameters)
{
SqlCommand cmd = new SqlCommand(query, conn, trans);
cmd.CommandType = queryType;
cmd.Parameters.AddRange(parameters);
return cmd.ExecuteScalar();
}
public static List<Lemma<double, string>> GetSigmaValues(SqlConnection conn, SqlTransaction trans, bool MDA)
{
List<Lemma<double, string>> lst = new List<Lemma<double, string>>();
lst.Add(new Lemma<double, string>(0d, ""));
using (SqlDataReader reader = DB.GetDataReader(conn, trans, MDA ? "csp_select_sigma_mda_values" : "csp_select_sigma_values", CommandType.StoredProcedure))
{
while(reader.Read())
lst.Add(new Lemma<double, string>(reader.GetDouble(0), reader.GetString(1)));
}
return lst;
}
public static List<Lemma<int?, string>> GetTopValues()
{
List<Lemma<int?, string>> lst = new List<Lemma<int?, string>>();
lst.Add(new Lemma<int?, string>(null, ""));
lst.Add(new Lemma<int?, string>(50, "50"));
lst.Add(new Lemma<int?, string>(500, "500"));
return lst;
}
public static void AddAuditMessage(SqlConnection conn, SqlTransaction trans, string tbl, Guid id, AuditOperationType op, string msg, string comment = "")
{
SqlCommand cmd = new SqlCommand("csp_insert_audit_log", conn, trans);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@id", Guid.NewGuid());
cmd.Parameters.AddWithValue("@source_table", tbl.Trim());
cmd.Parameters.AddWithValue("@source_id", id);
cmd.Parameters.AddWithValue("@operation", op.ToString());
cmd.Parameters.AddWithValue("@comment", comment.Trim());
cmd.Parameters.AddWithValue("@value", Utils.Compress(msg.Trim()));
cmd.Parameters.AddWithValue("@create_date", DateTime.Now);
cmd.ExecuteNonQuery();
}
public static List<Lemma<int, string>> GetIntLemmata(SqlConnection conn, SqlTransaction trans, string proc, bool addEmpty)
{
List<Lemma<int, string>> list = new List<Lemma<int, string>>();
if(addEmpty)
list.Add(new Lemma<int, string>(0, ""));
try
{
using (SqlDataReader reader = DB.GetDataReader(conn, trans, proc, CommandType.StoredProcedure))
{
while (reader.Read())
list.Add(new Lemma<int, string>(reader.GetInt32("id"), reader.GetString("name")));
}
}
catch (Exception ex)
{
Common.Log.Error(ex);
}
return list;
}
public static int GetNextSampleCount(SqlConnection conn, SqlTransaction trans)
{
SqlParameter nextNumber = new SqlParameter("@current_count", SqlDbType.Int) { Direction = ParameterDirection.Output };
SqlCommand cmd = new SqlCommand("csp_increment_sample_counter", conn, trans);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(nextNumber);
cmd.ExecuteNonQuery();
return Convert.ToInt32(nextNumber.Value);
}
public static bool LockSample(SqlConnection conn, Guid sampleId)
{
SqlTransaction trans = null;
try
{
trans = conn.BeginTransaction();
SqlCommand cmd = new SqlCommand("select locked_id from sample where id = @id", conn, trans);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@id", sampleId);
object o = cmd.ExecuteScalar();
if (!IsValidField(o))
{
cmd.CommandText = "update sample set locked_id = @locked_id where id = @id";
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("@locked_id", Common.UserId);
cmd.Parameters.AddWithValue("@id", sampleId);
cmd.ExecuteNonQuery();
trans.Commit();
if(!LockedSamples.Contains(sampleId))
LockedSamples.Add(sampleId);
return true;
}
else
{
trans.Commit();
Guid locked_id = Guid.Parse(o.ToString());
if(locked_id == Common.UserId)
{
if (!LockedSamples.Contains(sampleId))
LockedSamples.Add(sampleId);
return true;
}
return false;
}
}
catch(Exception ex)
{
trans?.Rollback();
Common.Log.Error(ex);
return false;
}
}
public static void UnlockSamples(SqlConnection conn)
{
try
{
SqlCommand cmd = new SqlCommand("update sample set locked_id = NULL where id = @id", conn);
cmd.CommandType = CommandType.Text;
foreach (Guid id in LockedSamples)
{
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("@id", id);
cmd.ExecuteNonQuery();
}
LockedSamples.Clear();
}
catch (Exception ex)
{
Common.Log.Error(ex);
}
}
public static bool LockOrder(SqlConnection conn, Guid orderId)
{
SqlTransaction trans = null;
try
{
trans = conn.BeginTransaction();
SqlCommand cmd = new SqlCommand("select locked_id from assignment where id = @id", conn, trans);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@id", orderId);
object o = cmd.ExecuteScalar();
if (!IsValidField(o))
{
cmd.CommandText = "update assignment set locked_id = @locked_id where id = @id";
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("@locked_id", Common.UserId);
cmd.Parameters.AddWithValue("@id", orderId);
cmd.ExecuteNonQuery();
trans.Commit();
if (!LockedOrders.Contains(orderId))
LockedOrders.Add(orderId);
return true;
}
else
{
trans.Commit();
Guid locked_id = Guid.Parse(o.ToString());
if(locked_id == Common.UserId)
{
if (!LockedOrders.Contains(orderId))
LockedOrders.Add(orderId);
return true;
}
return false;
}
}
catch (Exception ex)
{
trans?.Rollback();
Common.Log.Error(ex);
return false;
}
}
public static void UnlockOrders(SqlConnection conn)
{
try
{
SqlCommand cmd = new SqlCommand("update assignment set locked_id = NULL where id = @id", conn);
cmd.CommandType = CommandType.Text;
foreach (Guid id in LockedOrders)
{
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("@id", id);
cmd.ExecuteNonQuery();
}
LockedOrders.Clear();
}
catch (Exception ex)
{
Common.Log.Error(ex);
}
}
public static string GetOrderPrefix(SqlConnection conn, SqlTransaction trans, Guid labId)
{
SqlCommand cmd = new SqlCommand("select name_prefix from laboratory where id = @id", conn, trans);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@id", labId);
return cmd.ExecuteScalar().ToString();
}
public static int GetNextOrderCount(SqlConnection conn, SqlTransaction trans, Guid labId)
{
object o = GetScalar(conn, trans, "select last_assignment_counter_year from laboratory where id = @id", CommandType.Text, new[] {
new SqlParameter("@id", labId)
});
if (o == null || o == DBNull.Value)
throw new Exception("GetNextOrderCount: Unable to get last assignment counter year from database for lab id: " + labId.ToString());
int storedYear = Convert.ToInt32(o);
int currentYear = DateTime.Now.Year;
SqlCommand cmd = new SqlCommand("", conn, trans);
if (storedYear < currentYear)
{
cmd.CommandText = "update laboratory set last_assignment_counter_year = @year, assignment_counter = 1 where id = @id";
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@year", currentYear);
cmd.Parameters.AddWithValue("@id", labId);
cmd.ExecuteNonQuery();
}
SqlParameter nextNumber = new SqlParameter("@current_count", SqlDbType.Int) { Direction = ParameterDirection.Output };
cmd.CommandText = "csp_increment_assignment_counter";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("@laboratory_id", labId);
cmd.Parameters.Add(nextNumber);
cmd.ExecuteNonQuery();
return Convert.ToInt32(nextNumber.Value);
}
public static int GetSampleNumber(SqlConnection conn, SqlTransaction trans, Guid sampleId)
{
SqlCommand cmd = new SqlCommand("select number from sample where id = @sample_id", conn, trans);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@sample_id", sampleId);
object o = cmd.ExecuteScalar();
if (!IsValidField(o))
throw new Exception("Requested sample number not found for id: " + sampleId.ToString());
return Convert.ToInt32(o);
}
public static string GetGeometryName(SqlConnection conn, SqlTransaction trans, Guid geomId)
{
SqlCommand cmd = new SqlCommand("select name from preparation_geometry where id = @geometry_id", conn, trans);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@geometry_id", geomId);
object o = cmd.ExecuteScalar();
if (!IsValidField(o))
return "";
return o.ToString();
}
public static Guid GetLaboratoryIdFromOrderId(SqlConnection conn, SqlTransaction trans, Guid orderId)
{
SqlCommand cmd = new SqlCommand("select laboratory_id from assignment where id = @assignment_id", conn, trans);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@assignment_id", orderId);
object o = cmd.ExecuteScalar();
if (!IsValidField(o))
return Guid.Empty;
return Guid.Parse(o.ToString());
}
public static int GetNextPreparationNumber(SqlConnection conn, SqlTransaction trans, Guid sampleId)
{
SqlCommand cmd = new SqlCommand("select max(number) from preparation where sample_id = @sample_id", conn, trans);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@sample_id", sampleId);
object o = cmd.ExecuteScalar();
if (!IsValidField(o))
return 1;
return Convert.ToInt32(o) + 1;
}
public static int GetNextAnalysisNumber(SqlConnection conn, SqlTransaction trans, Guid prepId)
{
SqlCommand cmd = new SqlCommand("select max(number) from analysis where preparation_id = @prep_id", conn, trans);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@prep_id", prepId);
object o = cmd.ExecuteScalar();
if (!IsValidField(o))
return 1;
return Convert.ToInt32(o) + 1;
}
public static void LoadSampleTypes(SqlConnection conn, SqlTransaction trans)
{
Common.SampleTypeList.Clear();
using (SqlDataReader reader = DB.GetDataReader(conn, trans, "csp_select_sample_types", CommandType.StoredProcedure))
{
while (reader.Read())
{
SampleTypeModel sampleType = new SampleTypeModel(
reader.GetGuid("id"),
reader.GetGuid("parent_id"),
reader.GetString("name"),
reader.GetString("name_common"),
reader.GetString("name_latin"));
Common.SampleTypeList.Add(sampleType);
}
}
}
public static bool GetUniformActivity(SqlConnection conn, SqlTransaction trans, double activity, Guid activityUnitId, out double uActivity, out int uActivityUnitId)
{
SqlCommand cmd = new SqlCommand("select convert_factor, uniform_activity_unit_id from activity_unit where id = @id", conn, trans);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@id", activityUnitId);
using (SqlDataReader reader = cmd.ExecuteReader())
{
if (!reader.HasRows)
{
uActivity = 0d;
uActivityUnitId = 0;
return false;
}
reader.Read();
double convFactor = reader.GetDouble("convert_factor");
uActivityUnitId = reader.GetInt32("uniform_activity_unit_id");
uActivity = activity / convFactor;
}
return true;
}
public static Dictionary<string, Guid> GetNuclideNames(SqlConnection conn, SqlTransaction trans)
{
Dictionary<string, Guid> names = new Dictionary<string, Guid>();
names.Add("", Guid.Empty);
SqlCommand cmd = new SqlCommand("select id, name from nuclide order by name", conn, trans);
cmd.CommandType = CommandType.Text;
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
names.Add(reader.GetString("name").ToUpper(), reader.GetGuid("id"));
}
}
return names;
}
public static Dictionary<string, Guid> GetNuclideNamesForAnalysisMethod(SqlConnection conn, SqlTransaction trans, Guid analysisMethodId)
{
Dictionary<string, Guid> names = new Dictionary<string, Guid>();
names.Add("", Guid.Empty);
SqlCommand cmd = new SqlCommand(@"
select n.id, n.name
from nuclide n, analysis_method_x_nuclide amxn
where amxn.nuclide_id = n.id and amxn.analysis_method_id = @aid
order by n.name
", conn, trans);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@aid", analysisMethodId);
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
names.Add(reader.GetString("name").ToUpper(), reader.GetGuid("id"));
}
}
return names;
}
public static void LoadUserRoles(SqlConnection conn, SqlTransaction trans, Guid userId, ref List<string> userRoles)
{
userRoles.Clear();
string query = @"
select r.name
from role r
inner join account_x_role axr on axr.role_id = r.id and axr.account_id = @account_id
";
using (SqlDataReader reader = DB.GetDataReader(conn, trans, query, CommandType.Text, new[] {
new SqlParameter("@account_id", userId)
}))
{
while(reader.Read())
{
userRoles.Add(reader.GetString("name").ToUpper());
}
}
}
public static bool SpecRefExists(SqlConnection conn, SqlTransaction trans, string specref, Guid exceptId)
{
SqlCommand cmd = new SqlCommand("", conn, trans);
string query = "select count(*) from analysis where specter_reference = @specref and instance_status_id = 1";
cmd.Parameters.AddWithValue("@specref", specref);
if (exceptId != Guid.Empty)
{
query += " and id not in(@exId)";
cmd.Parameters.AddWithValue("@exId", exceptId);
}
cmd.CommandText = query;
int cnt = (int)cmd.ExecuteScalar();
if (cnt > 0)
return true;
return false;
}
public static void AddAttachment(SqlConnection conn, SqlTransaction trans, string sourceTable, Guid sourceId, string docName, string docExtension, byte[] data)
{
SqlCommand cmd = new SqlCommand("insert into attachment values(@id, @source_table, @source_id, @label, @file_extension, @content, @create_date, @create_id)", conn, trans);
cmd.Parameters.AddWithValue("@id", Guid.NewGuid());
cmd.Parameters.AddWithValue("@source_table", sourceTable);
cmd.Parameters.AddWithValue("@source_id", sourceId);
cmd.Parameters.AddWithValue("@label", docName);
cmd.Parameters.AddWithValue("@file_extension", docExtension);
cmd.Parameters.AddWithValue("@content", data);
cmd.Parameters.AddWithValue("@create_date", DateTime.Now);
cmd.Parameters.AddWithValue("@create_id", Common.UserId);
cmd.ExecuteNonQuery();
}
public static void DeleteAttachment(SqlConnection conn, SqlTransaction trans, string sourceTable, Guid sourceId)
{
SqlCommand cmd = new SqlCommand("delete from attachment where source_table = '" + sourceTable + "' and id = @id", conn, trans);
cmd.Parameters.AddWithValue("@id", sourceId);
cmd.ExecuteNonQuery();
}
public static void GetOrderRequiredInventory(SqlConnection conn, SqlTransaction trans, Guid assignmentId, out int nSamples, out int nPreparations, out int nAnalyses)
{
nSamples = nPreparations = nAnalyses = 0;
string query = @"
select
(
select sum(ast.sample_count)
from assignment a
inner join assignment_sample_type ast on ast.assignment_id = a.id
where a.id = @aid
) as 'nsamples',
(
select
sum(apm.preparation_method_count * ast.sample_count) as 'npreparations'
from assignment a
inner join assignment_sample_type ast on ast.assignment_id = a.id
inner join assignment_preparation_method apm on apm.assignment_sample_type_id = ast.id and apm.preparation_laboratory_id = a.laboratory_id
where a.id = @aid
) as 'npreparations',
(
select
sum(aam.analysis_method_count * apm.preparation_method_count * ast.sample_count) as 'nanalyses'
from assignment a
inner join assignment_sample_type ast on ast.assignment_id = a.id
inner join assignment_preparation_method apm on apm.assignment_sample_type_id = ast.id
left outer join assignment_analysis_method aam on aam.assignment_preparation_method_id = apm.id
where a.id = @aid
) as 'nanalyses'
";
using (SqlDataReader reader = DB.GetDataReader(conn, trans, query, CommandType.Text, new SqlParameter("@aid", assignmentId)))
{
if(reader.HasRows)
{
reader.Read();
if (IsValidField(reader["nsamples"]))
nSamples = reader.GetInt32("nsamples");
if (IsValidField(reader["npreparations"]))
nPreparations = reader.GetInt32("npreparations");
if (IsValidField(reader["nanalyses"]))
nAnalyses = reader.GetInt32("nanalyses");
}
}
}
public static void GetOrderCurrentInventory(SqlConnection conn, SqlTransaction trans, Guid assignmentId, out int nSamples, out int nPreparations, out int nAnalyses)
{
nSamples = nPreparations = nAnalyses = 0;
string query = @"
select
(
select count(*)
from sample s
inner join sample_x_assignment_sample_type sxast on sxast.sample_id = s.id
inner join assignment_sample_type ast on sxast.assignment_sample_type_id = ast.id
inner join assignment a on ast.assignment_id = a.id
where a.id = @aid
) as 'nsamples',
(
select count(*) from preparation p where p.assignment_id = @aid and p.instance_status_id < 2
) as 'npreparations',
(
select count(*) from analysis a where a.assignment_id = @aid and a.instance_status_id < 2
) as 'nanalyses'
";
using (SqlDataReader reader = DB.GetDataReader(conn, trans, query, CommandType.Text, new SqlParameter("@aid", assignmentId)))
{
if (reader.HasRows)
{
reader.Read();
if(IsValidField(reader["nsamples"]))
nSamples = reader.GetInt32("nsamples");
if (IsValidField(reader["npreparations"]))
nPreparations = reader.GetInt32("npreparations");
if (IsValidField(reader["nanalyses"]))
nAnalyses = reader.GetInt32("nanalyses");
}
}
}
public static void GetSampleCountForAST(SqlConnection conn, SqlTransaction trans, Guid astId, out int nSamples)
{
nSamples = 0;
string query = @"
select count(*) as 'nsamples'
from sample s
inner join sample_x_assignment_sample_type sxast on sxast.sample_id = s.id
inner join assignment_sample_type ast on sxast.assignment_sample_type_id = ast.id and sxast.assignment_sample_type_id = @astid
where s.instance_status_id < 2";
nSamples = (int)DB.GetScalar(conn, trans, query, CommandType.Text, new SqlParameter("@astid", astId));
}
public static int GetAvailableSamplesOnAssignmentSampleType(SqlConnection conn, SqlTransaction trans, Guid astId)
{
int nAvailSamples = 0, nCurrSamples = 0, n = 0;
string query = @"
select
(
select ast.sample_count from assignment_sample_type ast where ast.id = @ast_id
) as 'available_sample_count',
(
select count(*) from sample s
inner join sample_x_assignment_sample_type sxast on sxast.sample_id = s.id
inner join assignment_sample_type ast on sxast.assignment_sample_type_id = ast.id and ast.id = @ast_id
) as 'current_sample_count'
";
using (SqlDataReader reader = DB.GetDataReader(conn, trans, query, CommandType.Text, new SqlParameter("@ast_id", astId)))
{
if(reader.HasRows)
{
reader.Read();
if (IsValidField(reader["available_sample_count"]))
nAvailSamples = reader.GetInt32("available_sample_count");
if (IsValidField(reader["current_sample_count"]))
nCurrSamples = reader.GetInt32("current_sample_count");
n = nAvailSamples - nCurrSamples;
}
}
return n < 0 ? 0 : n;
}
public static bool IsValidField(object o)
{
return !(o == null || o == DBNull.Value);
}
public static bool NameExists(SqlConnection conn, SqlTransaction trans, string table, string name, Guid exceptId)
{
string query;
SqlCommand cmd = new SqlCommand("", conn, trans);
if (exceptId == Guid.Empty)
{
query = "select count(*) from " + table + " where name = @name";
cmd.Parameters.AddWithValue("@name", name);
}
else
{
query = "select count(*) from " + table + " where name = @name and id not in(@exId)";
cmd.Parameters.AddWithValue("@name", name);
cmd.Parameters.AddWithValue("@exId", exceptId);
}
cmd.CommandText = query;
return (int)cmd.ExecuteScalar() > 0;
}
public static bool CanUserApproveAnalysis(SqlConnection conn, SqlTransaction trans, Guid userId, Guid analMethId)
{
SqlCommand cmd = new SqlCommand("select count(*) from account_x_analysis_method where account_id = @acc_id and analysis_method_id = @am_id", conn, trans);
cmd.Parameters.AddWithValue("@acc_id", userId);
cmd.Parameters.AddWithValue("@am_id", analMethId);
return (int)cmd.ExecuteScalar() > 0;
}
public static double GetDouble(this SqlDataReader reader, string key)
{
if (!IsValidField(reader[key]))
throw new Exception("GetDouble: Invalid DB field: " + key);
return Convert.ToDouble(reader[key]);
}
public static double? GetDoubleNullable(this SqlDataReader reader, string key)
{
if (!IsValidField(reader[key]))
return null;
return Convert.ToDouble(reader[key]);
}
public static float GetSingle(this SqlDataReader reader, string key)
{
if (!IsValidField(reader[key]))
throw new Exception("GetSingle: Invalid DB field: " + key);
return Convert.ToSingle(reader[key]);
}
public static float? GetSingleNullable(this SqlDataReader reader, string key)
{
if (!IsValidField(reader[key]))
return null;
return Convert.ToSingle(reader[key]);
}
public static Int16 GetInt16(this SqlDataReader reader, string key)
{
if (!IsValidField(reader[key]))
throw new Exception("GetInt16: Invalid DB field: " + key);
return Convert.ToInt16(reader[key]);
}
public static Int16? GetInt16Nullable(this SqlDataReader reader, string key)
{
if (!IsValidField(reader[key]))
return null;
return Convert.ToInt16(reader[key]);
}
public static Int32 GetInt32(this SqlDataReader reader, string key)
{
if (!IsValidField(reader[key]))
throw new Exception("GetInt32: Invalid DB field: " + key);
return Convert.ToInt32(reader[key]);
}
public static Int32? GetInt32Nullable(this SqlDataReader reader, string key)
{
if (!IsValidField(reader[key]))
return null;
return Convert.ToInt32(reader[key]);
}
public static Int64 GetInt64(this SqlDataReader reader, string key)
{
if (!IsValidField(reader[key]))
throw new Exception("GetInt64: Invalid DB field: " + key);
return Convert.ToInt64(reader[key]);
}
public static Int64? GetInt64Nullable(this SqlDataReader reader, string key)
{
if (!IsValidField(reader[key]))
return null;
return Convert.ToInt64(reader[key]);
}
public static DateTime GetDateTime(this SqlDataReader reader, string key)
{
if (!IsValidField(reader[key]))
throw new Exception("GetDateTime: Invalid DB field: " + key);
return Convert.ToDateTime(reader[key]);
}
public static DateTime? GetDateTimeNullable(this SqlDataReader reader, string key)
{
if (!IsValidField(reader[key]))
return null;
return Convert.ToDateTime(reader[key]);
}
public static bool GetBoolean(this SqlDataReader reader, string key)
{
if (!IsValidField(reader[key]))
throw new Exception("GetBoolean: Invalid DB field: " + key);
return Convert.ToBoolean(reader[key]);
}
public static bool? GetBooleanNullable(this SqlDataReader reader, string key)
{
if (!IsValidField(reader[key]))
return null;
return Convert.ToBoolean(reader[key]);
}
public static string GetString(this SqlDataReader reader, string key)
{
if (!IsValidField(reader[key]))
return String.Empty;
return reader[key].ToString();
}
public static Guid GetGuid(this SqlDataReader reader, string key)
{
if (!IsValidField(reader[key]))
return Guid.Empty;
return Guid.Parse(reader[key].ToString());
}
public static string GetNameFromUsername(SqlConnection conn, SqlTransaction trans, string username)
{
object o = GetScalar(conn, trans, "select name + ' (' + email + ')' from cv_account where username = @username", CommandType.Text,
new SqlParameter("@username", username));
if (!IsValidField(o))
return String.Empty;
return o.ToString();
}
public static Guid GetSampleTypeParentId(SqlConnection conn, SqlTransaction trans, Guid sampleTypeId)
{
object o = GetScalar(conn, trans, "select parent_id from sample_type where id = @id", CommandType.Text,
new SqlParameter("@id", sampleTypeId));
if (!IsValidField(o))
return Guid.Empty;
return Guid.Parse(o.ToString());
}
public static bool HasAccessToOrder(SqlConnection conn, SqlTransaction trans, Guid orderId)
{
Guid aLabId = Assignment.GetLaboratoryId(conn, trans, orderId);
if (aLabId == Common.LabId)
return true;
Guid creatorId = Assignment.GetCreatorId(conn, trans, orderId);
if (creatorId == Common.UserId)
return true;
int n = (int)GetScalar(conn, trans, "select count(*) from assignment_x_account where assignment_id = @aid and account_id = @accid", CommandType.Text,
new SqlParameter("@aid", orderId),
new SqlParameter("@accid", Common.UserId));
if (n > 0)
return true;
return false;
}
public static bool HasAccessToSample(SqlConnection conn, SqlTransaction trans, Guid sampleId)
{
Guid labId = Sample.GetLaboratoryId(conn, trans, sampleId);
Guid creatorId = Sample.GetCreatorId(conn, trans, sampleId);
if (Common.LabId == Guid.Empty)
{
if (Common.UserId == creatorId)
return true;
}
else
{
if (Common.LabId == labId)
return true;
else if (Common.UserId == creatorId)
return true;
}
return false;
}
public static void InsertImportFileIdentifier(SqlConnection conn, SqlTransaction trans, Guid id)
{
string query = @"
begin
if not exists (select * from imported_file_identifiers where id = @id)
begin
insert into imported_file_identifiers values(@id)
end
end
";
SqlCommand cmd = new SqlCommand(query, conn, trans);
cmd.Parameters.AddWithValue("@id", id);
cmd.ExecuteNonQuery();
}
public static void CreateSampleParameterName(SqlConnection conn, SqlTransaction trans, string name, string type)
{
string query = @"
begin
if not exists (select * from sample_parameter_name where name = @name)
begin
insert into sample_parameter_name (id, name, type) values (@id, @name, @type)
end
end
";
SqlCommand cmd = new SqlCommand(query, conn, trans);
cmd.Parameters.AddWithValue("@id", Guid.NewGuid());
cmd.Parameters.AddWithValue("@name", name);
cmd.Parameters.AddWithValue("@type", type);
cmd.ExecuteNonQuery();
}
public static void InsertSampleParameter(SqlConnection conn, SqlTransaction trans, Guid sampleId, string parameterName, object parameterValue)
{
Guid pnId = (Guid)GetScalar(conn, trans, "select id from sample_parameter_name where name = @pname", CommandType.Text,
new SqlParameter("@pname", parameterName));
SqlCommand cmd = new SqlCommand("csp_insert_sample_parameter", conn, trans);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@id", Guid.NewGuid());
cmd.Parameters.AddWithValue("@sample_id", sampleId);
cmd.Parameters.AddWithValue("@sample_parameter_name_id", pnId);
cmd.Parameters.AddWithValue("@value", parameterValue.ToString());
cmd.Parameters.AddWithValue("@create_date", DateTime.Now);
cmd.Parameters.AddWithValue("@create_id", Common.UserId);
cmd.Parameters.AddWithValue("@update_date", DateTime.Now);
cmd.Parameters.AddWithValue("@update_id", Common.UserId);
cmd.ExecuteNonQuery();
}
public static bool HasAccreditationForOrderLine(SqlConnection conn, SqlTransaction trans, Guid labId, Guid sampleTypeId, Guid sampleComponentId, Guid prepMethId, Guid analMethId)
{
object o = GetScalar(conn, trans, "select path from sample_type where id = @id", CommandType.Text, new SqlParameter("@id", sampleTypeId));
if (o == null || o == DBNull.Value)
return false;
string findSampleTypePath = o.ToString().ToLower();
bool accredFound = false;
string query = @"
select a.*, st.id as 'sample_type_id', st.path as 'sample_type_path', sc.id as 'sample_component_id' from accreditation_term a
inner join accreditation_term_x_laboratory al on a.id = al.accreditation_term_id and al.laboratory_id = @laboratory_id
inner join accreditation_term_x_sample_type ast on a.id = ast.accreditation_term_id
left outer join sample_type st on st.id = ast.sample_type_id
inner join accreditation_term_x_preparation_method apm on a.id = apm.accreditation_term_id and apm.preparation_method_id = @preparation_method_id
inner join accreditation_term_x_analysis_method aam on a.id = aam.accreditation_term_id and aam.analysis_method_id = @analysis_method_id
left outer join accreditation_term_x_sample_type_x_sample_component ass on a.id = ass.accreditation_term_id and st.id = ass.sample_type_id
left outer join sample_component sc on sc.id = ass.sample_component_id
where a.instance_status_id = 1";
SqlCommand cmd = new SqlCommand(query, conn, trans);
using (SqlDataReader reader = DB.GetDataReader(conn, trans, query, CommandType.Text, new[] {
new SqlParameter("@laboratory_id", labId),
new SqlParameter("@preparation_method_id", prepMethId),
new SqlParameter("@analysis_method_id", analMethId)
}))
{
while(reader.Read())
{
Guid accredId = reader.GetGuid("id");
Guid sampTypeId = reader.GetGuid("sample_type_id");
Guid sampCompId = reader.GetGuid("sample_component_id");
string sampleTypePath = reader.GetString("sample_type_path").ToLower();
if (findSampleTypePath.StartsWith(sampleTypePath))
{
if(sampCompId != Guid.Empty)
{
if(sampCompId == sampleComponentId)
accredFound = true;
}
else
{
accredFound = true;
}
}
}
}
return accredFound;
}
}
public class SampleHeader
{
public Guid Id { get; set; }
public int Number { get; set; }
public string SampleTypeName { get; set; }
public string SampleComponentName { get; set; }
public string LaboratoryName { get; set; }
public List<PreparationHeader> Preparations = new List<PreparationHeader>();
public void Populate(SqlConnection conn, SqlTransaction trans)
{
if (Id == Guid.Empty)
return;
using (SqlDataReader reader = DB.GetDataReader(conn, trans, @"
select s.number, st.name as 'sample_type_name', sc.name as 'sample_component_name', l.name as 'laboratory_name'
from sample s
inner join sample_type st on st.id = s.sample_type_id
left outer join sample_component sc on sc.id = s.sample_component_id
inner join laboratory l on l.id = s.laboratory_id
where s.id = @sid
", CommandType.Text,
new SqlParameter("@sid", Id)))
{
reader.Read();
Number = reader.GetInt32("number");
SampleTypeName = reader.GetString("sample_type_name");
SampleComponentName = reader.GetString("sample_component_name");
LaboratoryName = reader.GetString("laboratory_name");
}
}
}
public class PreparationHeader
{
public Guid Id { get; set; }