forked from ChineduOpara/KCS.Common.Shared
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Extensions.cs
1638 lines (1478 loc) · 54.4 KB
/
Extensions.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
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using System.Xml;
namespace KCS.Common.Shared
{
/// <summary>
/// Contains general extension methods.
/// </summary>
public static class Extensions
{
private static Random _random = new Random();
public static T[] Shuffle<T>(this IEnumerable<T> array)
{
List<KeyValuePair<int, T>> list = new List<KeyValuePair<int, T>>();
// Add new random int each time
foreach (T s in array)
{
list.Add(new KeyValuePair<int, T>(_random.Next(), s));
}
// Sort the list by the random number
var sorted = from item in list
orderby item.Key
select item;
// Allocate new string array
T[] result = new T[array.Count()];
// Copy values to array
int index = 0;
foreach (KeyValuePair<int, T> pair in sorted)
{
result[index] = pair.Value;
index++;
}
// Return copied array
return result;
}
/// <summary>
/// Flashes a window.
/// </summary>
/// <param name="form">Form whose window will be flashed.</param>
public static void FlashWindow(this Form form)
{
FlashWindow(form, Win32API.User32.FlashWindow.UntilForeground);
}
/// <summary>
/// Flashes a window.
/// </summary>
/// <param name="form">Form whose window will be flashed.</param>
/// <param name="mode">Window flashing mode</param>
public static void FlashWindow(this Form form, Win32API.User32.FlashWindow mode)
{
Win32API.User32.FLASHWINFO fw = new Win32API.User32.FLASHWINFO();
fw.cbSize = Convert.ToUInt32(System.Runtime.InteropServices.Marshal.SizeOf(typeof(Win32API.User32.FLASHWINFO)));
fw.hwnd = form.Handle;
fw.dwFlags = (int)mode;
fw.uCount = UInt32.MaxValue;
Win32API.User32.FlashWindowEx(ref fw);
}
///// <summary>
///// Puts a blank row into the given datatable.
///// </summary>
///// <param name="dt"></param>
///// <param name="position">0-based position in which to insert the new row.</param>
///// <returns>Newly-added row.</returns>
//public static DataRow AddBlankRow(this DataTable dt, int position)
//{
// DataRow dr = dt.NewRow();
// foreach (DataColumn col in dt.Columns)
// {
// if (col.DefaultValue != null)
// {
// dr[col] = col.DefaultValue;
// }
// // If the column is still empty, but must have something in it, then use the default
// // of that particular type.
// if (Convert.IsDBNull(dr[col]) && !col.AllowDBNull && col.DataType.IsValueType)
// {
// dr[col] = Activator.CreateInstance(col.DataType);
// }
// }
// dt.Rows.InsertAt(dr, position);
// return dr;
//}
public static string GetErrorsCSV(this DataTable dt)
{
return string.Join(", ", dt.GetErrors().Select(x => x.RowError).ToArray());
}
/// <summary>
/// Make sure all the rows in a table have an Index, regardless of position. Skips deleted rows.
/// </summary>
public static void EnsureIndexes(this DataTable dt)
{
dt.EnsureColumn("INDEX", typeof(int));
DataRow[] currentRows = dt.Select("", "", DataViewRowState.CurrentRows);
for (int i = 0; i < currentRows.Length; i++)
{
DataRow dr = currentRows[i];
bool acceptChange = !Utility.IsRowReallyChanged(dr);
dr["INDEX"] = i;
if (acceptChange) dr.AcceptChanges();
}
}
/// <summary>
/// Make sure all the rows in the view have an Index.
/// </summary>
public static void EnsureIndexes(this DataView dv)
{
dv.Table.EnsureColumn("INDEX", typeof(int));
for (int i = 0; i < dv.Count; i++)
{
bool acceptChange = !Utility.IsRowReallyChanged(dv[i].Row);
dv[i]["INDEX"] = i;
if (acceptChange) dv[i].Row.AcceptChanges();
}
}
/// <summary>
/// Gets 2 columns of a table as a list of non-unique Key-Value pairs.
/// </summary>
/// <param name="dt">Table to work on.</param>
/// <param name="columnName">Name of the column that will be the key and value.</param>
/// <returns></returns>
public static IEnumerable<KeyValuePair<T, K>> GetDictionary<T, K>(this DataTable dt, string columnName)
{
return dt.GetDictionary<T, K>(columnName, columnName);
}
/// <summary>
/// Gets 2 columns of a table as a list of non-unique Key-Value pairs.
/// </summary>
/// <param name="table">Table to work on.</param>
/// <param name="keyColumnName">Name of the column that will be the keys.</param>
/// <param name="valueColumnName">Name of the column that will be the values.</param>
/// <returns></returns>
public static IEnumerable<KeyValuePair<T, K>> GetDictionary<T, K>(this DataTable table, string keyColumnName, string valueColumnName)
{
KeyValuePair<T, K> pair;
foreach (DataRow row in table.Rows)
{
T value1 = (T)Convert.ChangeType(row[keyColumnName], typeof(T));
K value2 = (K)Convert.ChangeType(row[valueColumnName], typeof(K));
pair = new KeyValuePair<T, K>(value1, value2);
yield return pair;
}
}
/// <summary>
/// Gets a list of all the values of a particular column, as a CSV.
/// </summary>
/// <param name="table">Table to work on.</param>
/// <param name="columnName">Name of the column to be extracted.</param>
/// <returns></returns>
public static string GetColumnValuesAsCSV(this DataTable table, string columnName)
{
var query = from row in table.Select()
select Convert.IsDBNull(row[columnName]) ? string.Empty : row[columnName].ToString();
return string.Join(",", query.ToArray());
}
/// <summary>
/// Gets a list of all the values of a particular column, as a List.
/// </summary>
/// <param name="table">Table to work on.</param>
/// <param name="columnName">Name of the column to be extracted.</param>
/// <returns></returns>
public static List<T> GetColumnValuesAsList<T>(this DataTable table, string columnName, bool distinct)
{
var query = from row in table.Select()
where (!(row[columnName] == null || Convert.IsDBNull(row[columnName])))
select (T)System.Convert.ChangeType(row[columnName], typeof(T));
if (distinct)
{
return query.Distinct().ToList();
}
else
{
return query.ToList();
}
}
/// <summary>
/// Gets a list of all the values of a particular column, as a List.
/// </summary>
/// <param name="table">Table to work on.</param>
/// <param name="columnName">Name of the column to be extracted.</param>
/// <returns></returns>
public static List<T> GetColumnValuesAsList<T>(this DataView dv, string columnName, bool distinct)
{
List<T> list = new List<T>();
foreach (DataRowView drv in dv)
{
if (drv[columnName] == null || Convert.IsDBNull(drv[columnName]))
continue;
list.Add((T)System.Convert.ChangeType(drv[columnName], typeof(T)));
}
if (distinct)
{
list = list.Distinct().ToList();
}
return list;
}
public static List<T> GetColumnValuesAsList<T>(this DataTable table, string columnName)
{
return GetColumnValuesAsList<T>(table, columnName, false);
}
public static List<T> GetColumnValuesAsList<T>(this DataView dv, string columnName)
{
return GetColumnValuesAsList<T>(dv, columnName, false);
}
/// <summary>
/// Reduces the columns in a table to a set list.
/// </summary>
/// <param name="table">Table to reduce.</param>
/// <param name="columnNames">Names of the columns to keep.</param>
public static void TrimToColumns(this DataTable table, params string[] columnNames)
{
TrimToColumns(table, columnNames.ToList());
}
/// <summary>
/// Reduces the columns in a table to a set list.
/// </summary>
/// <param name="table">Table to reduce.</param>
/// <param name="columnNames">Names of the columns to keep.</param>
public static void TrimToColumns(this DataTable table, IEnumerable<string> columnNames)
{
int index = 0;
// Make all the column names lowercase, to be sure comparison happens properly.
IList<string> list = columnNames.ToList();
for(int i = 0; i < list.Count; i++)
{
list[i] = list[i].ToLower();
}
// Drop all unnecessary columns from dt, to make it lighter.
do
{
if (list.Contains(table.Columns[index].ColumnName.ToLower()) || table.PrimaryKey.Contains(table.Columns[index]))
{
index++;
}
else
{
table.Columns.RemoveAt(index);
}
} while (index < table.Columns.Count);
}
public static void ClearExpressions(this DataTable dt)
{
foreach (DataColumn dc in dt.Columns)
{
if (!string.IsNullOrEmpty(dc.Expression))
{
dc.Expression = string.Empty;
}
}
}
public static void ClearRowErrors(this DataTable dt)
{
foreach (DataRow dr in dt.Rows)
{
dr.ClearErrors();
}
}
/// <summary>
/// Created by Georgi.
/// </summary>
/// <param name="dt"></param>
/// <param name="rowLimit"></param>
/// <returns></returns>
public static IEnumerable<DataTable> Split(this DataTable dt, int rowLimit)
{
if (rowLimit == 0) return new List<DataTable>(new DataTable[] { dt });
int size = dt.Rows.Count / rowLimit == 0 ? 1 : dt.Rows.Count / rowLimit;
List<DataTable> lstTables = new List<DataTable>(size);
int count = 0;
DataTable copyTable = null;
foreach (DataRow dr in dt.Rows)
{
if ((count % rowLimit) == 0)
{
copyTable = new DataTable(); // Clone the structure of the table.
copyTable = dt.Clone(); // Add the new DataTable to the list.
lstTables.Add(copyTable);
}
// Import the current row.
copyTable.ImportRow(dr);
count++;
}
return lstTables;
}
/// <summary>
/// Delegate to support the GetXML method.
/// </summary>
/// <param name="dr"></param>
/// <param name="columnName"></param>
/// <returns></returns>
public delegate string FormatDataForXMLDelegate(DataRow dr, string columnName);
/// <summary>
/// Gets the pure-XML for saving.
/// </summary>
/// <param name="dt">This datatable.</param>
/// <param name="rootElementName">Name of root element.</param>
/// <param name="formatDelegate">Method to be called in case we need special formatting.</param>
/// <returns>Well-formed XML.</returns>
public static string GetXML(this DataTable dt, string rootElementName, FormatDataForXMLDelegate formatDelegate)
{
XmlDocument doc = new XmlDocument();// Create the XML Declaration, and append it to XML document
XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", null, null);
doc.AppendChild(dec);// Create the root element
XmlElement root = doc.CreateElement(rootElementName);
doc.AppendChild(root);
foreach (DataRow dr in dt.Rows)
{
XmlElement elProd = doc.CreateElement(rootElementName);
root.AppendChild(elProd);
// Process all the columns. This is pretty straightforward
foreach (DataColumn column in dt.Columns)
{
XmlElement elRow = doc.CreateElement(column.ColumnName.ToLower());
if (formatDelegate == null)
{
elRow.InnerText = KCS.Common.Shared.Utility.GetStringValue(dr[column.ColumnName]);
}
else
{
elRow.InnerText = formatDelegate(dr, column.ColumnName);
}
elProd.AppendChild(elRow);
}
}
return doc.OuterXml;
}
/// <summary>
/// Sets the value in a row without disturbing the Modified flag.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dr"></param>
/// <param name="columnName"></param>
/// <param name="value"></param>
public static void SetValueWithoutModifyingRow<T>(this DataRow dr, string columnName, T value)
{
bool doAccept = !dr.HasVersion(DataRowVersion.Proposed);
dr[columnName] = value;
if (doAccept)
{
dr.AcceptChanges();
}
}
/// <summary>
/// Builds a filter from a list of columns.
/// </summary>
/// <param name="olumns"></param>
/// <param name="dr"></param>
public static string GetFilterForColumns(this DataRow dr, IEnumerable<string> columns)
{
return dr.GetFilterForColumns(columns, false);
}
/// <summary>
/// Builds a filter from a list of columns.
/// </summary>
/// <param name="olumns"></param>
/// <param name="dr"></param>
public static string GetFilterForColumns(this DataRow dr, IEnumerable<string> columns, bool treatNumericNullsAsZero)
{
List<string> filters = new List<string>(10);
foreach (string col in columns)
{
if (Convert.IsDBNull(dr[col]))
{
if (dr.Table.Columns[col].DataType.IsNumeric() && treatNumericNullsAsZero)
{
filters.Add(string.Format("{0} is null OR {0} = 0", col));
}
else
{
filters.Add(string.Format("{0} is null", col));
}
}
else
{
if (dr.Table.Columns[col].DataType.IsNumeric())
{
filters.Add(string.Format("{0} = {1}", col, dr[col]));
}
else
{
filters.Add(string.Format("{0} = '{1}'", col, dr[col]));
}
}
}
return string.Join(" AND ", filters.ToArray());
}
/// <summary>
/// Gets the values of a particular property of a DataColumn collection.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <remarks>This should be refactored to handle different inputs</remarks>
public static IEnumerable<T> GetColumnPropertyValue<T>(this DataColumnCollection dcCol, string propertyName)
{
Type type = typeof(DataColumn);
PropertyInfo prop = type.GetProperty(propertyName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.NonPublic);
if (prop == null)
{
throw new MissingMemberException(string.Format("The property \"{0}\" does not exist on type {1}", propertyName, type.FullName));
}
List<T> list = new List<T>(dcCol.Count);
foreach (DataColumn dc in dcCol)
{
object value = prop.GetValue(dc, null);
list.Add((T)Convert.ChangeType(value, typeof(T)));
}
return list;
}
/// <summary>
/// Determines whether a column has been changed.
/// </summary>
/// <param name="columnName">Column name</param>
/// <param name="row">the datarow</param>
/// <returns>true if its changed, else false</returns>
public static bool IsCellValueChanged(this DataRow row, string columnName)
{
// Added by COPARA 6/29/2010
if (string.IsNullOrEmpty(columnName)) return false;
if (row.RowState == DataRowState.Added) return true;
object original = row[columnName, DataRowVersion.Original];
object current = row[columnName, DataRowVersion.Current];
return Utility.ColChanged2(original, current);
}
/// <summary>
/// Gets a string of all the values in a DataRow.
/// </summary>
/// <param name="dr"></param>
/// <returns></returns>
/// <remarks>
/// 1. This does not check for custom data types.
/// </remarks>
public static string GetConcatenatedValues(this DataRow dr, params string[] columnNames)
{
StringBuilder sb = new StringBuilder();
foreach (string colname in columnNames)
{
sb.Append(Shared.Utility.GetStringValue(dr[colname]));
}
return sb.ToString();
}
/// <summary>
/// Gets the number of rows that were deleted.
/// </summary>
/// <returns></returns>
public static int GetDeletedRowCount(this DataTable dt)
{
DataRow[] rows = dt.Select("", "", DataViewRowState.Deleted);
return rows.Length;
}
/// <summary>
/// Gets the number of rows that were changed (added, modified, deleted).
/// </summary>
/// <returns></returns>
public static int GetChangedRowCount(this DataTable dt)
{
return dt.GetDeletedRowCount() + dt.GetModifiedRowCount() + dt.GetAddedRowCount();
}
/// <summary>
/// Gets the number of rows that were added.
/// </summary>
/// <returns></returns>
public static int GetAddedRowCount(this DataTable dt)
{
DataRow[] rows = dt.Select("", "", DataViewRowState.Added);
return rows.Length;
}
/// <summary>
/// Gets the number of rows that were modified.
/// </summary>
/// <returns></returns>
public static int GetModifiedRowCount(this DataTable dt)
{
int total = 0;
DataTable dtChanged = dt.GetChanges(DataRowState.Modified);
if (dtChanged != null && dtChanged.Rows.Count > 0)
{
foreach (DataRow dr in dtChanged.Rows)
{
foreach (DataColumn col in dt.Columns)
{
if (IsCellValueChanged(dr, col.ColumnName))
total++;
}
}
}
return total;
}
/// <summary>
/// Checks to see if any rows were changed or deleted.
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static bool IsAnyRowModified(this DataTable dt)
{
foreach (DataRow dr in dt.Select("", "", DataViewRowState.CurrentRows))
{
if (Utility.IsRowReallyChanged(dr))
return true;
}
DataRow[] deletedRows = dt.Select("", "", DataViewRowState.Deleted);
return deletedRows.Length > 0;
}
/// <summary>
/// Checks to see if any rows were added, changed or deleted.
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static bool IsChanged(this DataTable dt)
{
foreach (DataRow dr in dt.Select("", "", DataViewRowState.CurrentRows))
{
if (Utility.IsRowReallyChanged(dr))
return true;
}
DataRow[] deletedRows = dt.Select("", "", DataViewRowState.Deleted);
if (deletedRows.Length > 0)
{
return true;
}
DataRow[] newRows = dt.Select("", "", DataViewRowState.Added);
return newRows.Length > 0;
}
/// <summary>
/// Gets the center of a Rect.
/// </summary>
/// <param name="rect"></param>
/// <returns></returns>
public static Point Center(this Rectangle rect)
{
return new Point(rect.Left + rect.Width / 2, rect.Top + rect.Height / 2);
}
/// <summary>
/// Gets the hexcode representation of a color, without the # sign.
/// </summary>
/// <param name="color"></param>
/// <returns></returns>
public static string GetHexCode(this Color color)
{
return GetHexCode(color, false);
}
/// <summary>
/// Gets the hexcode representation of a color, without the # sign, with or without the alpha portion.
/// </summary>
/// <param name="color">Color to process</param>
/// <param name="includeAlpha">If true, the alpha value is included.</param>
/// <returns></returns>
public static string GetHexCode(this Color color, bool includeAlpha)
{
if (includeAlpha)
{
return string.Format("{0:X2}{1:X2}{2:X2}{3:X2}", color.A, color.R, color.G, color.B);
}
else
{
return string.Format("{0:X2}{1:X2}{2:X2}", color.R, color.G, color.B);
}
}
/*
/// <summary>
/// Gets the Color represented by an NCS code.
/// </summary>
/// <param name="c">Color.</param>
/// <param name="ncsCode">NCS code, complete with prefix and spaces. For example "S 3502-Y"</param>
/// <returns></returns>
public static Color FromNCS(this Color c, string ncsCode, out string errorMessage)
{
errorMessage = "";
try
{
int rgb = NCS.NCSUtils.NCSToRGB(ncsCode);
return Color.FromArgb(rgb);
}
catch (NCS.InvalidNCSCodeException ex)
{
errorMessage = ex.Message;
return System.Drawing.Color.Transparent;
}
}
public static Color FromNCS(this Color c, string ncsCode)
{
string errorMessage;
return FromNCS(c, ncsCode, out errorMessage);
}*/
/// <summary>
/// Gets a value from a DataRow, taking into consideration the possibility of it being DBNull.
/// </summary>
/// <param name="row">Row containing value.</param>
/// <param name="columnName">Column name.</param>
/// <param name="default">Default value.</param>
/// <returns>Column value, or default.</returns>
public static T GetValue<T>(this DataGridViewRow dr, string columnName)
{
if (Convert.IsDBNull(dr.Cells[columnName].Value))
{
return default(T);
}
else
{
return (T)Convert.ChangeType(dr.Cells[columnName].Value, typeof(T));
}
}
/// <summary>
/// Gets a value from a DataRow, taking into consideration the possibility of it being DBNull.
/// </summary>
/// <param name="row">Row containing value.</param>
/// <param name="columnName">Column name.</param>
/// <param name="default">Default value.</param>
/// <returns>Column value, or default.</returns>
public static T GetValue<T>(this DataRow dr, string columnName, T @default)
{
if (Convert.IsDBNull(dr[columnName]))
{
return @default;
}
else
{
return (T)Convert.ChangeType(dr[columnName], typeof(T));
}
}
public static T GetValue<T>(this DataRow dr, string columnName)
{
return dr.GetValue(columnName, default(T));
}
public static T GetValue<T>(this DataRowView drv, string columnName)
{
return drv.GetValue(columnName, default(T));
}
public static T GetValue<T>(this DataRowView drv, string columnName, T @default)
{
return drv.Row.GetValue(columnName, @default);
}
/// <summary>
/// Copies data from one row to another. Any columns that don't exist in the target row
/// are skipped.
/// </summary>
/// <param name="drTarget">Target row.</param>
/// <param name="dtSource">Source row.</param>
public static void CopyFrom(this DataRow drTarget, DataRow drSource)
{
foreach (DataColumn col in drSource.Table.Columns)
{
if (drTarget.Table.Columns.Contains(col.ColumnName))
{
drTarget[col.ColumnName] = drSource[col.ColumnName];
}
}
}
/// <summary>
/// Gets the DataRowView that matches the given DataRow.
/// </summary>
/// <param name="drTarget">Target row.</param>
public static DataRowView GetDataRowView(this DataRow dr)
{
DataRowView drvReturn = null;
foreach (DataRowView drv in dr.Table.DefaultView)
{
if (drv.Row == dr)
{
drvReturn = drv;
}
}
if (drvReturn == null) throw new Exception("This DataRow does not belong to a valid DataTable! Check your calling code!");
return drvReturn;
}
/// <summary>
/// Copies data of a particular version from one row to another. Any columns that don't exist in the target row
/// are skipped.
/// </summary>
/// <param name="drTarget">Target row.</param>
/// <param name="dtSource">Source row.</param>
public static void CopyFrom(this DataRow drTarget, DataRow drSource, DataRowVersion version)
{
foreach (DataColumn col in drSource.Table.Columns)
{
if (drTarget.Table.Columns.Contains(col.ColumnName))
{
if (drSource.HasVersion(version))
{
drTarget[col.ColumnName] = drSource[col.ColumnName, version];
}
else
{
drTarget[col.ColumnName] = drSource[col.ColumnName];
}
}
}
}
/// <summary>
/// Copies data from one row to another. Any columns that don't exist in the target row
/// are skipped.
/// </summary>
/// <param name="drTarget">Target row.</param>
/// <param name="dtSource">Source row.</param>
/// <returns>Number of fields copied.</returns>
public static uint CopyFrom(this DataRow drTarget, DataRow drSource, List<string> exclude)
{
uint counter = 0;
foreach (DataColumn col in drSource.Table.Columns)
{
if (!exclude.Contains(col.ColumnName) && drTarget.Table.Columns.Contains(col.ColumnName))
{
drTarget[col.ColumnName] = drSource[col.ColumnName];
counter++;
}
}
return counter;
}
public static string[] RemoveColumns(this DataTable dt, params string[] columns)
{
int i = 0;
var list = new List<string>();
do
{
var col = dt.Columns[i];
var contains = columns.Where(x => x.IndexOf(col.ColumnName, StringComparison.CurrentCultureIgnoreCase) > -1).Any();
if (contains)
{
list.Add(col.ColumnName);
dt.Columns.Remove(col);
}
else
{
i++;
}
} while (i < dt.Columns.Count);
return list.ToArray();
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dt"></param>
/// <param name="columns"></param>
/// <returns>The list of columns removed.</returns>
public static string[] PreserveColumns(this DataTable dt, params string[] columns)
{
int i = 0;
var list = new List<string>();
do
{
var col = dt.Columns[i];
var contains = columns.Where(x => x.IndexOf(col.ColumnName, StringComparison.CurrentCultureIgnoreCase) > -1).Any();
if (!contains)
{
list.Add(col.ColumnName);
dt.Columns.Remove(col);
}
else
{
i++;
}
} while (i < dt.Columns.Count);
return list.ToArray();
}
/// <summary>
/// Ensures that a table contains the given columns of the given type.
/// </summary>
/// <param name="dt">Datatable.</param>
/// <param name="type">Desired type of the columns.</param>
/// <param name="columns">Column Names.</param>
/// <returns>Number of columns added.</returns>
public static uint EnsureColumns<T>(this DataTable dt, params string[] columns)
{
uint counter = 0;
foreach (string name in columns)
{
//if (!dt.Columns.Contains(name.ToUpper()))
//{
// dt.Columns.Add(name.ToUpper(), type);
// counter++;
//}
if (!dt.Columns.Contains(name))
{
dt.Columns.Add(name, typeof(T));
counter++;
}
}
return counter;
}
/// <summary>
/// Ensures that a table contains the given columns.
/// </summary>
/// <param name="dt">Datatable.</param>
/// <param name="columns">Columns and matching types.</param>
public static uint EnsureColumns(this DataTable dt, params KeyValuePair<string, Type>[] columns)
{
uint counter = 0;
foreach (KeyValuePair<string, Type> pair in columns)
{
if (!dt.Columns.Contains(pair.Key))
{
dt.Columns.Add(pair.Key, pair.Value);
counter++;
}
}
return counter;
}
/// <summary>
/// Ensures that a table contains the given columns.
/// </summary>
/// <param name="dt">Datatable.</param>
/// <param name="columns">Columns and matching types.</param>
public static uint EnsureColumns(this DataTable dt, Dictionary<string, Type> columns)
{
uint counter = 0;
foreach (KeyValuePair<string, Type> pair in columns)
{
if (!dt.Columns.Contains(pair.Key))
{
dt.Columns.Add(pair.Key, pair.Value);
counter++;
}
}
return counter;
}
/// <summary>
/// Makes sure that a column is in the table.
/// </summary>
/// <param name="dt"></param>
/// <param name="name"></param>
public static DataColumn EnsureColumn(this DataTable dt, string name, Type type)
{
if (dt.Columns.Contains(name))
{
return dt.Columns[name];
}
else
{
return dt.Columns.Add(name, type);
}
}
/// <summary>
/// Makes sure that a string column is in the given table.
/// </summary>
/// <param name="dt"></param>
/// <param name="name"></param>
public static DataColumn EnsureColumn(this DataTable dt, string name)
{
return dt.EnsureColumn(name, typeof(string));
}
/// <summary>
/// Ensures that a given column is of the particular type.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dt"></param>
/// <param name="columnName"></param>
/// <param name="type"></param>
/// <returns></returns>
public static bool EnsureColumnIsType(this DataTable dt, string columnName, Type type)
{
List<int> failureIndexes;
return dt.EnsureColumnIsType(columnName, type, out failureIndexes);
}
/// <summary>
/// Ensures that a given column is of the particular type.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="dt"></param>
/// <param name="columnName"></param>
/// <param name="type"></param>
/// <returns></returns>
public static bool EnsureColumnIsType(this DataTable dt, string columnName, Type type, out List<int> failureIndexes)
{
int rowIndex = 0;
string tempColumnName = "Temp_Col_Name";
bool columnWasPrimaryKey = dt.PrimaryKey.Contains(dt.Columns[columnName]);
List<DataColumn> pKeys = null;
failureIndexes = new List<int>();
dt.EnsureColumn(tempColumnName, type);
foreach (DataRow dr in dt.Rows)
{
try
{
if (!Convert.IsDBNull(dr[columnName]))
{
dr[tempColumnName] = Convert.ChangeType(dr[columnName], type);
}
}
catch
{
failureIndexes.Add(rowIndex++);
}
}
// Remember to preserve the primary key
if (columnWasPrimaryKey)
{
pKeys = dt.PrimaryKey.ToList();
pKeys.Remove(dt.Columns[columnName]);
dt.PrimaryKey = null;
}
dt.Columns.Remove(columnName);
if (columnWasPrimaryKey)
{
pKeys.Add(dt.Columns[tempColumnName]);
dt.PrimaryKey = pKeys.ToArray();
}