-
Notifications
You must be signed in to change notification settings - Fork 0
/
Daber.cs
1131 lines (966 loc) · 39 KB
/
Daber.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
/*
The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy of the
License at http://www.mozilla.org/MPL/
Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
ANY KIND, either express or implied. See the License for the specific language governing rights and
limitations under the License.
The Original Code is Daber
The Initial Developer of the Original Code is Naveed Ahmed are Copyright (C) 2010. All Rights Reserved.
*/
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Text;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Data.Common;
namespace Daber
{
[System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Struct | System.AttributeTargets.Field)]
public class DBIgnore : System.Attribute
{
}
public delegate void DLogError(string s, Exception e);
public class DB
{
Dictionary<string, List<FieldInfo>> FieldInfoCache = new Dictionary<string, List<FieldInfo>>(); // Cache of all the fields of a class
Dictionary<string, Dictionary<string, int>> DBFieldIndexMaps = new Dictionary<string, Dictionary<string, int>>(); // Each dictionary contains an index of the column in the db for the respective field
Dictionary<string, Dictionary<string, string>> DBFieldMaps = new Dictionary<string, Dictionary<string, string>>(); // Mapping between class field (key) and db field (value)
protected List<string> ignoredClasses = new List<string>();
protected List<string> ignoredFields = new List<string>();
public List<string> IgnoredFields { get { return (this.ignoredFields); } set { this.ignoredFields = value; } }
/// <summary>
/// Use this to allow insertion of ids when identity is NOT set. Normally this field is ignored while inserting assuming that id is an identity column
/// </summary>
public bool InsertId = false;
string IdCol = "Id";
protected DLogError logError;
public DLogError LogError { get { return (this.logError); } set { this.logError = value; } }
IConnector connector;
public DB(IConnector connector)
{
this.connector = connector;
}
/// <summary>
/// Gets a single row/object. Condition should be specifed in the list
/// </summary>
/// <typeparam name="T">Class of object</typeparam>
/// <param name="table">Table Name</param>
/// <param name="getColumn">The columns to get, you can use "*" or "col1, col2 ..." </param>
/// <param name="conditionList"> conditionList has column name and value pairs. The default condition operation is '=', to use '>' or '<' add the operator at the end of the column</param>
/// <returns>The row with the object or null if no results</returns>
public T Get<T>(string table, string getColumn, params object[] conditionList)
{
List<T> l = GetList<T>(table, getColumn, null, null, conditionList);
if (l == null || l.Count == 0)
return default(T);
return l[0];
}
/// <summary>
/// Gets a single row/object. Condition should be specifed in the list
/// </summary>
/// <typeparam name="T">Class of object</typeparam>
/// <param name="table">Table Name</param>
/// <param name="getColumn">The columns to get, you can use "*" or "col1, col2 ..." </param>
/// <param name="extraCondition">And additional conditions that might not be key value pairs that cannot go in the conditionList. Use null if no extra condition.</param>
/// <param name="conditionList"> conditionList has column name and value pairs. The default condition operation is '=', to use '>' or '<' add the operator at the end of the column</param>
/// <returns>The row with the object or null if no results</returns>
public T GetWithCondition<T>(string table, string getColumn, string extraCondition, params object[] conditionList)
{
List<T> l = GetList<T>(table, getColumn, null, extraCondition, conditionList);
if (l == null || l.Count == 0)
return default(T);
return l[0];
}
/// <summary>
/// Get a list of rows/objects from a table
/// list has column name and value pairs. The default condition operation is '=', to use <, >, <=, =>, != OR 'LIKE' add the operator at the end of the column
/// The default conjunction between column name value pairs is 'AND'. Suffix ' OR' to use OR instead.
/// </summary>
/// <typeparam name="T">Class of object</typeparam>
/// <param name="table">Table Name</param>
/// <param name="getColumn">The columns to get, you can use "*" or "col1, col2 ..." </param>
/// <param name="orderColumn">The column(s) tor order the results by. Use null if no ordering necessary.</param>
/// <param name="extraCondition">And additional conditions that might not be key value pairs that cannot go in the conditionList. Use null if no extra condition.</param>
/// <param name="conditionList"> conditionList has column name and value pairs. The default condition operation is '=', to use '>' or '<' add the operator at the end of the column</param>
/// <returns></returns>
public List<T> GetList<T>(string table, string getColumn, string orderColumn, string extraCondition, params object[] conditionList)
{
if (conditionList.Length % 2 != 0)
{
throw new Exception("Number of columns does not match number of values in GetList");
}
string cmdText = "";
//DbCommand cmd = new DbCommand();
DbCommand cmd = connect();
StringBuilder condition = null;
condition = new StringBuilder(buildCondition(cmd, conditionList));
if (!string.IsNullOrEmpty(extraCondition))
{
if (condition.ToString() != "")
condition.Append(" AND ");
condition.Append(" " + extraCondition);
}
if (condition.Length > 0)
cmdText = string.Format("SELECT {0} FROM {1} WHERE {2}", getColumn, table, condition);
else
cmdText = string.Format("SELECT {0} FROM {1}", getColumn, table);
if (!string.IsNullOrEmpty(orderColumn))
cmdText += string.Format(" ORDER BY {0}", orderColumn);
return getList<T>(cmd, cmdText);
}
/// <summary>
/// Returns a list of objects of the class T. T should have the same fields specified in the select query in cmdText
/// Use this to use your own select query
/// The order of the parameters in the query should match the order of parameter values
/// The parameters can be repeated in the query, but the order of parameters in the query
/// should still match the parameter values
/// </summary>
/// <typeparam name="T">Class of the return type</typeparam>
/// <param name="cmdText">Select Query</param>
/// <param name="list">List of parameter values only (not key value pairs) for the query</param>
/// <returns></returns>
public List<T> GetListQuery<T>(string cmdText, params object[] list)
{
//DbCommand cmd = new DbCommand();
DbCommand cmd = connect();
return getList<T>(cmd, cmdText, list);
}
/// <summary>
/// Returns an object of the class T. T should have the same fields specified in the select query in cmdText
/// Use this to use your own select query
/// The order of the parameters in the query should match the order of parameter values
/// The parameters can be repeated in the query, but the order of parameters in the query
/// should still match the parameter values
/// </summary>
/// <typeparam name="T">Class of the return type</typeparam>
/// <param name="cmdText">Select Query</param>
/// <param name="list">List of parameter values for the query</param>
/// <returns></returns>
public T GetQuery<T>(string cmdText, params object[] list)
{
List<T> l = GetListQuery<T>(cmdText, list);
if (l == null || l.Count == 0)
return default(T);
return l[0];
}
/// <summary>
/// Update a table
/// conditionList has column name and value pairs.
/// The default condition operation is '=', to use '>', '<', '>=' or '<=' add the operator at the end of the column
/// To set the value of one column from another column or more like col1 = col2 + col3, suffix the first column with '='
/// </summary>
/// <param name="table">Table Name</param>
/// <param name="numUpdateCols">The number of column value pairs that are columns to be updated</param>
/// <param name="conditionList">First include the column-value pairs to be updated and then the column-value pair conditions</param>
/// <returns>Number of rows updated. -1 for error/exception</returns>
public int Update(string table, string extraCondition, int numUpdateCols, params object[] conditionList)
{
int ret = 0;
if (conditionList.Length % 2 != 0)
{
throw new Exception("Number of columns does not match number of values in Update");
}
if (numUpdateCols > conditionList.Length)
throw new Exception("numUpdateCols > list.Length");
DbCommand cmd = null;
try
{
cmd = connect();
object[] conditions = new object[conditionList.Length - numUpdateCols * 2];
Array.Copy(conditionList, numUpdateCols * 2, conditions, 0, conditionList.Length - numUpdateCols * 2);
StringBuilder condition = new StringBuilder(buildCondition(cmd, conditions));
if (!string.IsNullOrEmpty(extraCondition))
{
if (condition.ToString() != "")
condition.Append(" AND ");
condition.Append(" " + extraCondition);
}
StringBuilder updates = new StringBuilder();
for (int i = 0; i < numUpdateCols * 2; i += 2)
{
object oVal = conditionList[i + 1];
string col = conditionList[i].ToString();
if (col.EndsWith("="))
{
col = col.Substring(0, col.Length - 1); // remove the '='
updates.AppendFormat("{0} = {1},", col, oVal);
}
else
{
updates.AppendFormat("{0}=@updateValue{1},", col, i / 2);
addParameter(cmd, "@updateValue" + i / 2, oVal);
}
}
updates.Remove(updates.Length - 1, 1); // Remove the comma
cmd.CommandText = string.Format("UPDATE {0} SET {1} WHERE {2}", table, updates, condition);
ret = cmd.ExecuteNonQuery();
}
catch (Exception e)
{
if (logError != null)
logError("Exception in Update " + buildLogCondition(conditionList), e);
ret = -1;
}
finally
{
close(cmd);
}
return ret;
}
/// <summary>
/// Delete rows from a table
/// </summary>
/// <param name="table">Table Name</param>
/// <param name="conditionList"> conditionList has column name and value pairs. The default condition operation is '=', to use '>' or '<' add the operator at the end of the column</param>
/// <returns></returns>
public int Delete(string table, params object[] conditionList)
{
if (conditionList.Length % 2 != 0)
{
throw new Exception("Number of columns does not match number of values in Delete");
}
int ret = 0;
DbCommand cmd = null;
try
{
cmd = connect();
string condition = buildCondition(cmd, conditionList);
if (conditionList == null || conditionList.Length == 0 || string.IsNullOrEmpty(condition))
cmd.CommandText = string.Format("DELETE FROM {0}", table);
else
cmd.CommandText = string.Format("DELETE FROM {0} WHERE {1}", table, condition);
ret = cmd.ExecuteNonQuery();
}
catch (Exception e)
{
if (logError != null)
logError("Exception in Delete from" + table + " WHERE " + buildLogCondition(conditionList), e);
ret = -1;
}
finally
{
close(cmd);
}
return ret;
}
/// <summary>
/// Insert a new item/row in the table
/// </summary>
/// <typeparam name="T">Class of table/item</typeparam>
/// <param name="table">Table Name</param>
/// <param name="item">Item/Row to be inserted</param>
/// <returns></returns>
public int Insert<T>(string table, T item)
{
if (item == null)
return 0;
List<T> list = new List<T>(1);
list.Add(item);
return Insert<T>(table, list);
}
/// <summary>
/// Insert a new item/row in the table, but returns the id of the inserted item
/// </summary>
/// <typeparam name="T">Class of table/item</typeparam>
/// <param name="table">Table Name</param>
/// <param name="item">Item/Row to be inserted</param>
/// <param name="id">Returns the auto-incremented or IDENTITY primary key value of the newly added row</param>
/// <returns></returns>
public int Insert<T>(string table, T item, out long id)
{
id = 0;
if (item == null)
return 0;
List<T> list = new List<T>(1);
list.Add(item);
return Insert<T>(table, list, out id);
}
/// <summary>
/// Insert list of multiple objects
/// </summary>
/// <typeparam name="T">Class of object</typeparam>
/// <param name="table">Table Name</param>
/// <param name="list"></param>
/// <returns>number of rows successfully inserted</returns>
public int Insert<T>(string table, List<T> list)
{
long id = 0;
return Insert<T>(table, list, out id);
}
/// <summary>
/// Insert list of multiple objects
/// </summary>
/// <typeparam name="T">Class of object</typeparam>
/// <param name="table">Table Name</param>
/// <param name="list"></param>
/// /// <param name="id">Returns the auto-incremented or IDENTITY primary key value of the LAST newly added row</param>
/// <returns>number of rows successfully inserted</returns>
public int Insert<T>(string table, List<T> list, out long id)
{
id = 0;
if (list == null || list.Count == 0)
return 0;
List<FieldInfo> fields = getFields(typeof(T));
Dictionary<string, string> dbFieldMap = getDBFieldMap(table, typeof(T));
int rows = 0;
DbCommand cmd = null;
try
{
cmd = connect();
for (int i = 0; i < list.Count; i++)
{
StringBuilder sbCols = new StringBuilder();
StringBuilder sbVals = new StringBuilder();
cmd.Parameters.Clear();
object oVal = list[i];
for (int j = 0; j < fields.Count; j++)
{
FieldInfo fi = fields[j];
if (Ignore(fi))
continue;
if (!InsertId && fi.Name.Equals(IdCol, StringComparison.CurrentCultureIgnoreCase))
continue;
string col = dbFieldMap[fi.Name];
object fieldValue = fi.GetValue(oVal);
addToInsertString(cmd, j, col, fieldValue, ref sbCols, ref sbVals);
}
sbCols.Remove(sbCols.Length - 2, 2); // Remove the comma
sbVals.Remove(sbVals.Length - 2, 2); // Remove the comma
rows = connector.Insert(cmd, table, sbCols.ToString(), sbVals.ToString(), out id);
}
}
catch (Exception ex)
{
if (logError != null)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("Table: " + table);
foreach (T item in list)
{
sb.AppendLine(ObjectString(item));
}
logError("InsertIntoDB: \r\n" + sb.ToString(), ex);
}
rows = -1;
}
finally
{
close(cmd);
}
return rows;
}
/// <summary>
/// Use this to execute a complex SQL non query like UPDATE, INSERT OR DELETE where the existing Update, Insert or Delete methods cannot be used.
/// </summary>
/// <param name="cmdText">The SQL non-query</param>
/// <param name="list">The parameter values</param>
/// <returns></returns>
public int ExecuteNonQuery(string cmdText, params object[] list)
{
DbCommand cmd = null;
int rows = 0;
try
{
cmd = connect();
for (int i = 0; i < list.Length; i++)
{
string col = "v" + i;
object o = list[i];
addParameter(cmd, col, o);
}
cmd.CommandText = cmdText;
rows = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
if (logError != null)
logError("Exception in DB.ExecuteNonQuery", ex);
rows = -1;
}
finally
{
close(cmd);
}
return rows;
}
/// <summary>
/// Goes through all the fields in the object and generates a string, useful for debugging
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
public string ObjectString(object o, int indent = 1)
{
StringBuilder sb = new StringBuilder();
List<FieldInfo> fields = getFields(o.GetType());
string tabs = new string('\t', indent);
for (int j = 0; j < fields.Count; j++)
{
FieldInfo fi = fields[j];
if (Ignore(fi))
continue;
object fieldValue = fi.GetValue(o);
sb.AppendLine(tabs + fi.Name + ": " + (fieldValue ?? "*NULL*"));
}
return sb.ToString();
}
/// <summary>
/// Converts db field name format to class field format - removes underscores and capitalizes the words
/// </summary>
/// <param name="dbFieldName"></param>
/// <returns></returns>
public static string DBToCodeFieldName(string column)
{
int diff = 'a' - 'A';
StringBuilder sb = new StringBuilder(column.Length);
char[] ca = column.ToLower().ToCharArray();
bool newWord = true;
for (int i = 0; i < ca.Length; i++)
{
char c = ca[i];
if (newWord)
c = (char)(Convert.ToInt32(ca[i]) - diff);
if (c == '_' || c == ' ')
{
newWord = true;
}
else
{
sb.Append(c);
newWord = false;
}
}
return sb.ToString();
}
/// <summary>
/// Add a custom mapping of db Column to class field. Use this if the db field and class name don't match
/// </summary>
/// <param name="list">alternate db column followed by class field name</param>
public void AddFieldIndexMap(Type t, params string[] list)
{
if (list.Length % 2 != 0)
{
throw new Exception("Number of columns does not match number of fields in AddFieldIndexMap");
}
for (int i = 0; i < list.Length; i += 2)
{
string col = list[i];
string classFieldName = list[i + 1];
}
Dictionary<string, int> map = new Dictionary<string, int>(list.Length / 2);
List<FieldInfo> fields = getFields(t);
for (int i = 0; i < list.Length; i += 2)
{
string dbFieldName = list[i];
string classFieldName = list[i + 1];
for (int j = 0; j < fields.Count; j++)
{
if (fields[j].Name.Equals(classFieldName, StringComparison.CurrentCultureIgnoreCase))
{
map.Add(dbFieldName, j);
break;
}
}
}
DBFieldIndexMaps.Add(t.Name, map);
}
/// <summary>
/// Returns an intersection of the provided lists
/// </summary>
/// <param name="a">Sorted list</param>
/// <param name="b">Sorted list</param>
/// <returns></returns>
public static List<int> Intersect(List<int> a, List<int> b)
{
List<int> result = new List<int>(a.Count + b.Count);
if (a == null || a.Count == 0)
return result;
else if (b == null || b.Count == 0)
return result;
int i = 0, j = 0;
while (i < a.Count && j < b.Count)
{
while (i < a.Count && j < b.Count && a[i] < b[j])
i++;
bool added = false;
while (i < a.Count && j < b.Count && a[i] == b[j])
{
if (!added) // to avoid duplicates
result.Add(a[i]);
added = true;
i++;
j++;
}
while (i < a.Count && j < b.Count && a[i] > b[j])
j++;
}
return result;
}
static int CompareFieldInfo(FieldInfo x, FieldInfo y)
{
if (x == null)
{
if (y == null)
return 0;
else
return -1;
}
else
{
if (y == null)
return 1;
else
{
if (x.Name == y.Name)
return 0;
if (x.Name == "id")
return -1;
if (y.Name == "id")
return 1;
if (IsClass(x.FieldType) != IsClass(y.FieldType))
{
if (IsClass(x.FieldType)) // We want classes to be at the end
return 1;
else
return -1;
}
return x.Name.CompareTo(y.Name);
}
}
}
static bool IsClass(Type t)
{
return (t.IsClass && t.Name != "String" && !IsStringArray(t));
}
static bool IsArray(FieldInfo fi)
{
return (fi.FieldType.IsArray || (fi.FieldType.FullName.IndexOf("System.Collections.Generic.List") >= 0) && !IsStringArray(fi));
}
static bool IsStringArray(FieldInfo fi)
{
return (fi.FieldType.FullName.IndexOf("System.Collections.Generic.List`1[[System.String") >= 0);
}
static bool IsStringArray(Type t)
{
return (t.FullName.IndexOf("System.Collections.Generic.List`1[[System.String") >= 0);
}
List<T> getList<T>(DbCommand cmd, string cmdText, params object[] list)
{
List<T> ret = new List<T>();
try
{
cmd.CommandText = cmdText;
addParameters(cmd, list);
DbDataReader reader = cmd.ExecuteReader();
if (reader != null)
{
Type obType = typeof(T);
List<FieldInfo> fields = getFields(typeof(T));
Dictionary<string, int> dbFieldIndexMap = null;
if (IsClass(obType))
dbFieldIndexMap = getDBFieldIndexMap(typeof(T), reader);
while (reader.Read())
{
object o = null;
if (IsClass(obType))
{
ConstructorInfo ci = obType.GetConstructor(new Type[] { });
if (ci == null)
throw new Exception(string.Format("{0} does not have a default constructor", obType.Name));
o = ci.Invoke(null);
for (int i = 0; i < reader.FieldCount; i++)
{
string dbField = reader.GetName(i);
if (!dbFieldIndexMap.ContainsKey(dbField))
continue;
int fieldIndex = dbFieldIndexMap[dbField];
FieldInfo fi = fields[fieldIndex];
string fieldName = fi.Name;
object dbValue = reader[i];
if (dbValue.GetType() == typeof(DBNull))
{
// do nothing
}
else if (dbValue.GetType() == typeof(Int64) && fi.FieldType == typeof(Int32))
{
Int32 n = Convert.ToInt32(dbValue);
fi.SetValue(o, n);
}
else if (dbValue.GetType() == typeof(string) && fi.FieldType == typeof(Guid))
{
string s = dbValue.ToString();
fi.SetValue(o, new Guid(s));
}
else if (fi.FieldType.IsEnum)
{
if (dbValue.GetType() == typeof(decimal))
fi.SetValue(o, Enum.ToObject(fi.FieldType, Decimal.ToInt32((decimal)dbValue)));
else
fi.SetValue(o, Enum.ToObject(fi.FieldType, dbValue));
}
else if (fi.FieldType == typeof(double) || fi.FieldType == typeof(double?))
{
double n = Convert.ToDouble(dbValue);
fi.SetValue(o, n);
}
else if (fi.FieldType == typeof(int) && dbValue.GetType() == typeof(decimal))
fi.SetValue(o, Decimal.ToInt32((decimal)dbValue));
else if (fi.FieldType == typeof(long) && dbValue.GetType() == typeof(decimal))
fi.SetValue(o, Decimal.ToInt64((decimal)dbValue));
else if (fi.FieldType == typeof(bool))
fi.SetValue(o, Convert.ToBoolean(dbValue));
else if (fi.FieldType == typeof(DateTime))
fi.SetValue(o, Convert.ToDateTime(dbValue));
else if (!IsArray(fi))
fi.SetValue(o, dbValue);
else if (fi.FieldType.IsEnum)
{
if (Enum.GetUnderlyingType(fi.FieldType) == typeof(Byte))
fi.SetValue(o, Convert.ToByte(dbValue));
else if (Enum.GetUnderlyingType(fi.FieldType) == typeof(short))
fi.SetValue(o, Convert.ToInt16(dbValue));
else if (Enum.GetUnderlyingType(fi.FieldType) == typeof(int))
fi.SetValue(o, Convert.ToInt32(dbValue));
}
else
throw new Exception(string.Format("Could not handle field '{0}' of type '{0}' in query '{1}'", fieldName, fi.FieldType, cmdText));
}
ret.Add((T)o);
}
else
{
if (reader.IsDBNull(0))
ret.Add(default(T));
else if (typeof(T) == typeof(Int32) || typeof(T) == typeof(Int32?))
ret.Add((T)(object)Convert.ToInt32(reader.GetInt32(0)));
else if(typeof(T) == typeof(UInt32) || typeof(T) == typeof(UInt32?))
ret.Add((T)(object)Convert.ToUInt32(reader.GetInt32(0)));
else if (typeof(T) == typeof(string))
ret.Add((T)(object)reader.GetString(0));
else if (typeof(T) == typeof(DateTime) || typeof(T) == typeof(DateTime?))
ret.Add((T)(object)reader.GetDateTime(0));
else if (typeof(T) == typeof(ulong) || typeof(T) == typeof(long))
ret.Add((T)(object)reader.GetInt64(0));
else if (typeof(T) == typeof(Guid))
ret.Add((T)(object)reader.GetGuid(0));
else if (typeof(T) == typeof(short))
ret.Add((T)(object)reader.GetInt16(0));
else if (typeof(T) == typeof(Decimal))
ret.Add((T)(reader.GetValue(0)));
else if (typeof(T) == typeof(double))
{
object d = Convert.ToDouble(reader.GetValue(0));
ret.Add((T)d);
}
else if (typeof(T) == typeof(byte))
ret.Add((T)(reader.GetValue(0)));
else if (typeof(T) == typeof(bool) || typeof(T) == typeof(bool?))
{
ret.Add((T)(reader.GetValue(0)));
}
else
throw new Exception("Return type not supported: " + typeof(T));
}
}
reader.Close();
}
}
catch (Exception e)
{
if (logError != null)
{
StringBuilder condition = new StringBuilder();
getLoggableConditionString(condition, list);
logError(string.Format("Exception in GetList {0}", condition.ToString()), e);
}
}
finally
{
close(cmd);
}
return ret;
}
/// <summary>
/// Converts the condition string to a loggable kind - replaces the parameter place holders (@v0, @v1 ...) with actual values
/// </summary>
/// <param name="sb"></param>
/// <param name="list"></param>
protected static void getLoggableConditionString(StringBuilder sb, object[] list)
{
for (int i = 0; i < list.Length; i += 2)
{
object obValue = null;
int index = (int)(i / 2);
if (i + 1 < list.Length)
obValue = list[i + 1];
string valString = "@v" + index;
sb.Replace(valString, obValue.ToString());
}
}
/// <summary>
/// Get the fields from a given Type. Cached.
/// </summary>
/// <param name="t">the Type</param>
/// <returns></returns>
List<FieldInfo> getFields(Type t)
{
List<FieldInfo> fields = null;
if (FieldInfoCache.ContainsKey(t.Name))
fields = FieldInfoCache[t.Name];
else
{
FieldInfo[] _fields = t.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
fields = new List<FieldInfo>(_fields);
fields.Sort(CompareFieldInfo);
FieldInfoCache.Add(t.Name, fields);
}
return fields;
}
Dictionary<string, int> getDBFieldIndexMap(Type t, DbDataReader reader)
{
Dictionary<string, int> map = null;
if (DBFieldIndexMaps.ContainsKey(t.Name))
map = DBFieldIndexMaps[t.Name];
else
{
map = new Dictionary<string, int>(reader.FieldCount);
List<FieldInfo> fields = getFields(t);
for (int i = 0; i < reader.FieldCount; i++)
{
string dbFieldName = reader.GetName(i);
string codeFieldName = DBToCodeFieldName(dbFieldName);
for (int j = 0; j < fields.Count; j++)
{
if (fields[j].Name.Equals(codeFieldName, StringComparison.CurrentCultureIgnoreCase) || fields[j].Name.Equals(dbFieldName, StringComparison.CurrentCultureIgnoreCase))
{
map.Add(dbFieldName, j);
break;
}
}
}
DBFieldIndexMaps.Add(t.Name, map);
}
return map;
}
/// <summary>
/// Builds the condition part of the query
/// list has column name and value pairs. The default condition operation is '=', to use '>' or '<' add the operator at the end of the column
/// </summary>
/// <param name="cmd"></param>
/// <param name="list"></param>
/// <returns></returns>
protected string buildCondition(DbCommand cmd, params object[] list)
{
if (cmd == null || list == null || list.Length == 0)
return "";
string AND = " AND ";
string OR = " OR ";
string sConj = AND;
char[] whiteSpace = " \t\r\n".ToCharArray();
StringBuilder sbCondition = new StringBuilder();
for (int i = 0; i < list.Length; i += 2)
{
sConj = AND;
object oVal = list[i + 1];
string col = list[i].ToString();
if (col.EndsWith(OR.TrimEnd(whiteSpace), StringComparison.CurrentCultureIgnoreCase))
{
col = col.Remove(col.Length - OR.TrimEnd(whiteSpace).Length);
sConj = OR;
}
if (oVal == null || (oVal is string && oVal.ToString() == ""))
{
if (col.LastIndexOf("!=") == col.Length - 2)
sbCondition.Append(col.Substring(0, col.Length - 2) + " IS NOT NULL" + sConj);
else
sbCondition.Append(col + " IS NULL" + sConj);
}
else
{
string parName = "@v" + ((int)(i / 2)).ToString();
string like = " LIKE";
if (col.Length > like.Length && col.Substring(col.Length - like.Length).Equals(like, StringComparison.CurrentCultureIgnoreCase))
sbCondition.Append(col + " " + parName + sConj);
else if (col.LastIndexOf(">=") == col.Length - 2)
sbCondition.Append(col.Substring(0, col.Length - 2) + " >= " + parName + sConj);
else if (col.LastIndexOf("<=") == col.Length - 2)
sbCondition.Append(col.Substring(0, col.Length - 2) + " <= " + parName + sConj);
else if (col.LastIndexOf("!=") == col.Length - 2)
sbCondition.Append(col.Substring(0, col.Length - 2) + " != " + parName + sConj);
else if (col.LastIndexOf('>') == col.Length - 1)
sbCondition.Append(col.Substring(0, col.Length - 1) + " > " + parName + sConj);
else if (col.LastIndexOf('<') == col.Length - 1)
sbCondition.Append(col.Substring(0, col.Length - 1) + " < " + parName + sConj);
else
sbCondition.Append(col + " = " + parName + sConj);
addParameter(cmd, parName, oVal);
}
}
sbCondition.Remove(sbCondition.Length - sConj.Length, sConj.Length); // Remove the AND
return sbCondition.ToString();
}
/// <summary>
/// Builds the condition string for logging. Mainly used for exception logging
/// </summary>
/// <param name="list"></param>
/// <returns></returns>
protected string buildLogCondition(params object[] list)
{
if (list == null || list.Length == 0)
return "";
string sAND = " AND ";
StringBuilder sbCondition = new StringBuilder();
for (int i = 0; i < list.Length; i += 2)
{
object oVal = list[i + 1];
string col = list[i].ToString();
if (oVal == null || (oVal is string && oVal.ToString() == ""))
{
sbCondition.Append(col + " IS NULL" + sAND);
}
else
{
string parName = oVal.ToString();
if (col.LastIndexOf('>') == col.Length - 1)
sbCondition.Append(col.Substring(0, col.Length - 1) + " > " + parName + sAND);
else if (col.LastIndexOf('<') == col.Length - 1)
sbCondition.Append(col.Substring(0, col.Length - 1) + " < " + parName + sAND);
else
sbCondition.Append(col + " = " + parName + sAND);
}
}
sbCondition.Remove(sbCondition.Length - sAND.Length, sAND.Length); // Remove the AND
return sbCondition.ToString();
}
protected Dictionary<string, string> getDBFieldMap(string table, Type t)
{
if (DBFieldMaps.ContainsKey(table))
return DBFieldMaps[table];
List<FieldInfo> fields = getFields(t);
DbCommand cmd = null;
Dictionary<string, string> map = null;
try
{
cmd = connect();
cmd.CommandText = "SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '" + table.ToUpper() + "' order by column_name";
DbDataReader reader = cmd.ExecuteReader();
if (reader == null)
return null;
map = new Dictionary<string, string>(fields.Count);
while (reader.Read())
{
string dbFieldName = reader.GetString(3);
string codeFieldName = DBToCodeFieldName(dbFieldName);