-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAnonymousTypeConversion.cs
More file actions
1346 lines (1135 loc) · 41.9 KB
/
AnonymousTypeConversion.cs
File metadata and controls
1346 lines (1135 loc) · 41.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Reflection;
using System.Data;
using System.IO;
using System.Text;
using Metaphone;
using EmTrac2SF.EMSC2SF;
namespace GenericLibrary
{
public static class Util
{
public static string FirstNonNull( params string[] strValues )
{
foreach( string strValue in strValues )
if( strValue != null && ! strValue.Equals( "" ) )
return strValue;
return "";
}
public static string ToNormalizedMetaphone( this string strMain )
{
string strMainNbrs = Util.GetNumbersInString( strMain );
string strMPMain = string.Concat( strMainNbrs, Util.NormalizeForMatching( strMain ) );
return strMPMain;
}
public static string ToMetaphone( this string strMain )
{
string strMainNbrs = Util.GetNumbersInString( strMain );
string strMPMain = string.Concat( strMainNbrs, Util.Metaphone( strMain ) );
return strMPMain;
}
public static bool HasNumbers( this string strValue )
{
System.Text.RegularExpressions.Regex objRegex = new System.Text.RegularExpressions.Regex( @"\d+" );
// detect numbers from the string to match
System.Text.RegularExpressions.Match objMatch = objRegex.Match( strValue );
return objMatch.Success;
}
public static bool HasLetters( this string strValue )
{
System.Text.RegularExpressions.Regex objRegex = new System.Text.RegularExpressions.Regex( @"[a-zA-Z]+" );
// detect letters from the string to match
System.Text.RegularExpressions.Match objMatch = objRegex.Match( strValue );
return objMatch.Success;
}
public static string GetNumbersInString( string strValue )
{
if( strValue == null )
return "";
char[] buffer = new char[ strValue.Length ];
int idx = 0;
foreach( char c in strValue )
{
// this only collects digits and spaces
if( c == ' ' || ( c >= '0' && c <= '9' ) )
{
buffer[ idx ] = c;
idx++;
}
}
return new string( buffer, 0, idx );
//System.Text.RegularExpressions.Regex objRegex = new System.Text.RegularExpressions.Regex( @"\d+" );
//// extract numbers from the column to match, if needed
//System.Text.RegularExpressions.Match objMatch = objRegex.Match( strValue );
//if( objMatch.Success )
// return objMatch.Value;
//return "";
}
public static string TrimUpToSeparator( string strValue )
{
// get only what is before a dash/comma in a name
int iPos = strValue.IndexOfAny( ",-/".ToCharArray() );
if( iPos > 0 )
return strValue.Substring( 0, iPos );
return strValue;
}
public static string Metaphone( string strName )
{
// convert to sorted metaphone
MultiWordMetaphone objMWM = new MultiWordMetaphone();
objMWM.Name = strName;
return objMWM.MetaphoneKey;
}
//public static string[] strNonAlpha = { "-", ".", ",", "@", "$", "#", "(", ")", "/", "'" };
public static char[] strNonAlpha = { '-', '.', ',', '@', '$', '#', '(', ')', '/', '\'' };
// always use LOWERCASE
public static string[] strSearchFor = { " & ", " + ", " saint ", " west ", " east ", " north ", " south ", " avenue "
, " road ", " street ", " lane ", " po box ", " p o box ", " drive "
, " parkway ", " boulevard ", " insurance ", " university ", " program ", " college "
, " fort ", " school ", " medicine ", " som ", " center ", " cente ", " cnt "
, " air force base ", " air force ", " hlth ", " sci ", " hospital ", " institute " };
// always use LOWERCASE
public static string[] strSubstitutions = { " and ", " and ", " st ", " w ", " e ", " n ", " s ", " ave "
, " rd ", " st ", " ln ", " pobox ", " pobox ", " dr "
, " pkwy ", " blvd ", " ins ", " univ ", " prog ", " coll "
, " ft ", " sch ", " med ", " school of medicine ", " ctr ", " ctr ", " ctr "
, " usaf ", " usaf ", " health ", " sciences ", " hosp ", " inst" };
// always use LOWERCASE
public static string[] strWordsToRemove = { " company ", " co ", " corp ", " corporation ", " inc ", " incorporated "
, " ltd ", " limited ", " plc ", " llc ", " corporation of america ", " the "
, " dept of ", " department of ", " suite ", " group ", " grp ", " assoc ", " asso ", " association " };
// words to keep separate (example: match AtlantiCare with Atlanti-Care)
public static string[] strWordsToSeparate = { "care", "health" };
public static string NormalizeForMatching( string strName )
{
// prepare string for search/replace/removal
string strKey = string.Concat( " ", strName.ToLower(), " " );
// remove special characters
strKey = strKey.ReplaceSpecialCharacters( "" );
// remove non-alpha characters: dashes, dots, commas
strKey = strKey.ReplaceCharacters( strNonAlpha, ' ' );
//strKey = strKey.ReplaceKeywords( strNonAlpha, "" );
// replace & or + with "and"
strKey = strKey.ReplaceKeywords( strSearchFor, strSubstitutions );
// remove prefixes and suffixes
strKey = strKey.ReplaceKeywords( strWordsToRemove, "" );
// separate words
strKey = strKey.SeparateKeywords( strWordsToSeparate );
// remove unneeded spaces
strKey = strKey.Trim().Replace( " ", " " ).Replace( " ", " " );
// convert to sorted metaphone
strKey = Metaphone( strKey );
return strKey;
}
public static string[] strAMAInstitSearch = { " Sch Of Med ", " Coll Of Med ", " Inst "
, " Med ", " Sch ", " Coll ", " Sci " }; //, " Univ "
public static string[] strAMAInstitReplace = { " School of Medicine ", " College of Medicine ", " Institute "
, " Medical ", " School ", " College ", " Sciences " }; //, " University "
public static string NormalizeAMAInstitution( string strName )
{
strName = string.Concat( " ", strName, " " );
strName = strName.ReplaceKeywords( strAMAInstitSearch, strAMAInstitReplace ).Trim();
return strName;
}
public static string Capitalize( string strValue )
{
if( strValue == null ) return null;
return System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase( strValue.ToLower() );
}
public static string CapitalizeWithStateCode( string strValue )
{
if( strValue == null ) return null;
strValue = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase( strValue.ToLower() );
string strStatePattern = "[ ][A-Z][a-z]$";
strValue = System.Text.RegularExpressions.Regex.Replace( strValue, strStatePattern
, delegate( System.Text.RegularExpressions.Match match )
{
string strMatch = match.ToString();
return strMatch.ToUpper();
} );
return strValue;
}
}
public static class FileToObject
{
public static string ToSalesForceCSVString<T>( this T objT, string strColsToInclude = "" ) where T : sObject
{
// get individual column names from the list
string[] strColumns = strColsToInclude.Split( ",".ToCharArray() );
// store column info in the order received in the list
List<PropertyInfo> objList = new List<PropertyInfo>( strColumns.Count() );
foreach( string strCol in strColumns )
{
PropertyInfo objP = objT.GetType().GetProperty( strCol );
if( objP != null )
objList.Add( objP );
}
// concatenate values separated by comma
StringBuilder strbResult = new StringBuilder( strColumns.Count() * 15 );
foreach( PropertyInfo objP in objList )
{
object objValue = objP.GetValue( objT, null );
if( objValue != null )
{
string strColType = objP.PropertyType.ToString();
switch( strColType )
{
case "System.String":
// if value has commas, enclose it in quotes
strbResult.Append( FixCSV( objValue.ToString() ) );
break;
case "System.DateTime": case "System.Nullable`1[System.DateTime]":
strbResult.Append( FixCSV( (DateTime) objValue ) );
break;
default:
strbResult.Append( objValue.ToString() );
break;
}
}
strbResult.Append( "," );
}
//objSW.AppendLine( strbLine.ToString().Substring( 1 ) );
// remove last comma
strbResult.Remove( strbResult.Length - 1, 1 );
strbResult.AppendLine();
return strbResult.ToString();
}
public static string ToSalesForceCSVString( this DataTable objDT )
{
StringBuilder objSW = new StringBuilder();
// write column headers
StringBuilder strbLine = new StringBuilder();
foreach( DataColumn objDC in objDT.Columns )
{
strbLine.Append( "," );
strbLine.Append( objDC.ColumnName );
}
objSW.AppendLine( strbLine.ToString().Substring( 1 ) );
// write column values for each row
foreach( DataRow objDR in objDT.Rows )
{
// write line with column values
strbLine = new StringBuilder();
for( int iColIndex = 0; iColIndex < objDT.Columns.Count; iColIndex++ )
{
strbLine.Append( "," );
if( !Convert.IsDBNull( objDR[ iColIndex ] ) )
{
string strColType = objDR[ iColIndex ].GetType().ToString();
switch( strColType )
{
case "System.String":
strbLine.Append( FixCSV( objDR[ iColIndex ].ToString() ) );
break;
case "System.DateTime":
strbLine.Append( FixCSV( (DateTime) objDR[ iColIndex ] ) );
break;
default:
strbLine.Append( objDR[ iColIndex ].ToString() );
break;
}
}
}
objSW.AppendLine( strbLine.ToString().Substring( 1 ) );
}
return objSW.ToString();
}
public static string SaveAsSalesForceCSV( this DataTable objDT, string strFileName )
{
StreamWriter objSW = new StreamWriter( strFileName, false );
// write column headers
StringBuilder strbLine = new StringBuilder(1100000); // max = 1.1 Kb per 2500 rows
foreach( DataColumn objDC in objDT.Columns )
{
strbLine.Append( "," );
strbLine.Append( objDC.ColumnName );
}
objSW.WriteLine( strbLine.ToString().Substring( 1 ) );
// write column values for each row
foreach( DataRow objDR in objDT.Rows )
{
// write line with column values
strbLine = new StringBuilder();
for( int iColIndex = 0; iColIndex < objDT.Columns.Count; iColIndex ++ )
{
strbLine.Append( "," );
if( !Convert.IsDBNull( objDR[ iColIndex ] ) )
{
string strColType = objDR[ iColIndex ].GetType().ToString();
switch( strColType )
{
case "System.String":
strbLine.Append( FixCSV( objDR[ iColIndex ].ToString() ) );
break;
case "System.DateTime":
strbLine.Append( FixCSV( (DateTime) objDR[ iColIndex ] ) );
break;
default:
strbLine.Append( objDR[ iColIndex ].ToString() );
break;
}
}
}
objSW.WriteLine( strbLine.ToString().Substring( 1 ) );
}
objSW.Close();
return "";
}
public static string FixCSV( DateTime dtValue )
{
if( dtValue.Year > 2035 )
return "2005-" + dtValue.Month.ToString("d2") + "-" + dtValue.Day.ToString("d2");
return dtValue.ToString( "yyyy-MM-dd" );
}
public static string FixCSV( string strValue )
{
return "\"" + strValue.Replace("\"", "\"\"") + "\"";
}
/// <summary>
/// Reads CSV file into a list of objects by placing each value in the respective object's members
/// </summary>
public static List<T> ReadFile<T>( this List<T> arr, string strFileName, string strColumnNames, bool bSkip1stRow = false )
{
List<T> obj = new List<T>();
StreamReader objSR = new StreamReader( strFileName );
string strLine;
if( bSkip1stRow )
strLine = objSR.ReadLine();
while( ( strLine = objSR.ReadLine() ) != null )
arr.Add( strLine.ConvertTo<T>( strColumnNames ) );
objSR.Dispose();
return arr;
}
/// <summary>
/// Reads CSV file into a DataTable by placing each value in a column
/// </summary>
public static DataTable ReadFile( this DataTable objDT, string strFileName, string strColumnNames, bool b1stRowIsHeader = false )
{
StreamReader objSR = new StreamReader( strFileName );
if( objDT == null ) objDT = new DataTable();
string[] strSpecifiedCols = strColumnNames.Split( ',' );
string strLine;
if( b1stRowIsHeader )
{
// read 1st row/header to decide what names to give the columns
strLine = objSR.ReadLine();
string[] strCols = strLine.Split( ',' );
int iIndex = 0;
foreach( string strColumnName in strCols )
{
// only use column name from header if the column was not specified in the list
string strName = strSpecifiedCols[ iIndex ];
if( strName.Equals( "" ) )
{
// remove quotes since this is coming from a CSV file
strName = strColumnName.Replace( "\"", "" );
strSpecifiedCols[ iIndex ] = strName;
}
// create column with the name given, otherwise, the name from the header
DataColumn objDC = new DataColumn( strName, typeof( string ) );
objDT.Columns.Add( objDC );
iIndex++;
}
}
while( ( strLine = objSR.ReadLine() ) != null )
{
// place each value in the respective column
string[] strValues = strLine.Split( ',' );
int iIndex = 0;
DataRow objDR = objDT.NewRow();
foreach( string strColumnName in strSpecifiedCols )
{
string strValue = strValues[ iIndex ];
// if the value starts with a quote but doesn't have an ending quote,
// then the value may have been split by a comma
if( strValue.StartsWith( "\"" ) && !strValue.EndsWith( "\"" ) )
// keep appending to the value until finding an ending quote
while( iIndex < strValues.Count() && !strValues[ iIndex ].EndsWith( "\"" ) )
{
iIndex++;
strValue = string.Concat( strValue, ",", strValues[ iIndex ] );
}
//if( strColumnNames.Length <= iColIndex )
// break;
//string strColName = strColumnNames[ iColIndex ];
//if( strColName.Equals( "" ) )
//{
// iColIndex++;
// continue;
//}
if( strValue.StartsWith( "\"" ) )
strValue = strValue.Remove( 0, 1 );
if( strValue.EndsWith( "\"" ) )
strValue = strValue.Remove( strValue.Length - 1, 1 );
// store column value without non-printable characters
objDR[ strColumnName ] = strValue.ReplaceSpecialCharacters( "" );
iIndex++;
}
// add new row to the table
objDT.Rows.Add( objDR );
}
objSR.Dispose();
return objDT;
}
}
public static class AnonymousTypeConversion
{
/// <summary>
/// Converts a single DataRow object into something else.
/// The destination type must have a default constructor.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="objDR"></param>
/// <returns></returns>
public static T ConvertTo<T>( this DataRow objDR )
{
T item = Activator.CreateInstance<T>();
for( int f = 0; f < objDR.Table.Columns.Count; f++ )
{
string strColName = objDR.Table.Columns[ f ].ColumnName;
PropertyInfo p = item.GetType().GetProperty( strColName );
if( p == null )
continue;
object objValue = objDR.Field<object>( strColName );
// can't convert string to nullable datetime here
// so check the target type p.PropertyType
if( p.PropertyType == typeof( DateTime? ) )// && objType == typeof(string))
{
DateTime? dtValue = null;
if( objValue != null && !objValue.ToString().Equals( "" ) )
dtValue = Convert.ToDateTime( objValue );
p.SetValue( item, dtValue, null );
}
else if( p.PropertyType == typeof( Boolean? ) )
{
Boolean? bValue = null;
if( objValue != null && !objValue.ToString().Equals( "" ) )
{
if( objValue.ToString().Equals( "-1" ) )
bValue = true;
else if( objValue.ToString().Equals( "0" ) )
bValue = false;
else
bValue = Convert.ToBoolean( objValue );
}
p.SetValue( item, bValue, null );
}
else if( p.PropertyType == typeof( Decimal? ) )
{
Decimal? decValue = null;
if( objValue != null && !objValue.ToString().Equals( "" ) )
decValue = Convert.ToDecimal( objValue );
p.SetValue( item, decValue, null );
}
else if( p.PropertyType == typeof( Int32? ) || p.PropertyType == typeof( Int32 ) )
{
Int32? iValue = null;
if( objValue != null && !objValue.ToString().Equals( "" ) )
iValue = Convert.ToInt32( objValue );
p.SetValue( item, iValue, null );
}
else if( p.PropertyType == typeof( Double? ) )
{
Double? dblValue = null;
if( objValue != null && !objValue.ToString().Equals( "" ) )
dblValue = Convert.ToDouble( objValue );
p.SetValue( item, dblValue, null );
}
else if( p.PropertyType == typeof( string ) )
{
string strValue = null;
if( objValue != null )
strValue = objValue.ToString();
p.SetValue( item, strValue, null );
}
else
p.SetValue( item, objValue, null );
}
return item;
}
/// <summary>
/// Converts a single DataRow object into something else.
/// The destination type must have a default constructor.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="objDR"></param>
/// <returns></returns>
public static T ConvertTo<T>(this DataRow objDR, bool bFuzzyColumnMatch = false )
{
T item = Activator.CreateInstance<T>();
for (int f = 0; f < objDR.Table.Columns.Count; f++)
{
string strColName = objDR.Table.Columns[f].ColumnName;
Type objType = objDR.Table.Columns[f].DataType;
PropertyInfo p = item.GetType().GetProperty(strColName);
if (bFuzzyColumnMatch)
{
// if property name doesn't match, try removing spaces
if (p == null)
{
string strNameUnderscore = strColName.Replace(" ", "");
p = item.GetType().GetProperty(strNameUnderscore);
}
// if property name doesn't match, try replacing spaces with underscore
if (p == null)
{
string strNameUnderscore = strColName.Replace(' ', '_');
p = item.GetType().GetProperty(strNameUnderscore);
}
// if property name doesn't match, try lowercase minus initial
if (p == null)
{
string strCapitalizedInitial = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(strColName);
p = item.GetType().GetProperty(strCapitalizedInitial);
}
// if property name still doesn't match, try appending __c
if (p == null)
{
string strCustomName = string.Concat(strColName, "__c");
p = item.GetType().GetProperty(strCustomName);
}
// if property name doesn't match, try lowercase minus initial and appending __c
if (p == null)
{
string strCustomName = string.Concat(strColName, "__c");
string strCapitalizedInitial = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(strCustomName);
p = item.GetType().GetProperty(strCapitalizedInitial);
}
if (p == null)
if (strColName.Contains("Name"))
p = item.GetType().GetProperty("Name");
}
if (p == null)
continue;
object objValue = objDR.Field<object>(strColName);
// can't convert string to nullable datetime here
// so check the target type p.PropertyType
if (p.PropertyType == typeof(DateTime?) )// && objType == typeof(string))
{
DateTime? dtValue = null;
if (objValue != null && !objValue.ToString().Equals(""))
dtValue= Convert.ToDateTime(objValue);
p.SetValue(item, dtValue, null);
}
else if( p.PropertyType == typeof(Boolean?) )
{
Boolean? bValue = null;
if (objValue != null && !objValue.ToString().Equals(""))
{
if (objValue.ToString().Equals("-1"))
bValue = true;
else if (objValue.ToString().Equals("0"))
bValue = false;
else
bValue = Convert.ToBoolean(objValue);
}
p.SetValue(item, bValue, null);
}
else if (p.PropertyType == typeof(Decimal?))
{
Decimal? decValue = null;
if (objValue != null && !objValue.ToString().Equals(""))
decValue = Convert.ToDecimal(objValue);
p.SetValue(item, decValue, null);
}
else if (p.PropertyType == typeof(Int32?) || p.PropertyType == typeof(Int32))
{
Int32? iValue = null;
if (objValue != null && !objValue.ToString().Equals(""))
iValue = Convert.ToInt32(objValue);
p.SetValue(item, iValue, null);
}
else if (p.PropertyType == typeof(Double?))
{
Double? dblValue = null;
if (objValue != null && !objValue.ToString().Equals(""))
dblValue = Convert.ToDouble(objValue);
p.SetValue(item, dblValue, null);
}
else if (p.PropertyType == typeof(string))
{
string strValue = null;
if (objValue != null)
strValue = objValue.ToString();
p.SetValue(item, strValue, null);
}
else
p.SetValue(item, objValue, null);
}
return item;
}
/// <summary>
/// Converts a string of CSV into an object placing each value into the object's members
/// </summary>
public static T ConvertTo<T>(this string strCSVRow, string strNames )
{
string[] strValues = strCSVRow.Split(',');
string[] strColumnNames = strNames.Split(',');
T item = Activator.CreateInstance<T>();
int iColIndex = 0;
for (int f = 0; f < strValues.Count(); f++)
{
// check whether the value is enclosed in quotes
string strValue = strValues[ f ];
// if the value starts with a quote but doesn't have an ending quote,
// then the value may have been split by a comma
if( strValue.StartsWith( "\"" ) && ! strValue.EndsWith( "\"" ) )
// keep appending to the value until finding an ending quote
while( f < strValues.Count() && ! strValues[ f ].EndsWith( "\"" ) )
{
f ++;
strValue = string.Concat( strValue, ",", strValues[ f ] );
}
if( strColumnNames.Length <= iColIndex )
break;
string strColName = strColumnNames[ iColIndex ];
if( strColName.Equals( "" ) )
{
iColIndex++;
continue;
}
if( strValue.StartsWith( "\"" ) )
strValue = strValue.Remove( 0, 1 );
if( strValue.EndsWith( "\"" ) )
strValue = strValue.Remove( strValue.Length - 1, 1 );
object objValue = strValue;
PropertyInfo p = item.GetType().GetProperty(strColName);
// if property name doesn't match, try removing spaces
if (p == null)
{
string strNameUnderscore = strColName.Replace(" ", "");
p = item.GetType().GetProperty(strNameUnderscore);
}
// if property name doesn't match, try replacing spaces with underscore
if (p == null)
{
string strNameUnderscore = strColName.Replace(' ', '_');
p = item.GetType().GetProperty(strNameUnderscore);
}
// if property name doesn't match, try lowercase minus initial
if (p == null)
{
string strCapitalizedInitial = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(strColName);
p = item.GetType().GetProperty(strCapitalizedInitial);
}
// if property name still doesn't match, try appending __c
if (p == null)
{
string strCustomName = string.Concat(strColName, "__c");
p = item.GetType().GetProperty(strCustomName);
}
// if property name doesn't match, try lowercase minus initial and appending __c
if (p == null)
{
string strCustomName = string.Concat(strColName, "__c");
string strCapitalizedInitial = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(strCustomName);
p = item.GetType().GetProperty(strCapitalizedInitial);
}
if (p == null)
if (strColName.Contains("Name"))
p = item.GetType().GetProperty("Name");
if( p == null )
{
iColIndex++;
continue;
}
// can't convert string to nullable datetime here
// so check the target type p.PropertyType
if (p.PropertyType == typeof(DateTime?))// && objType == typeof(string))
{
DateTime? dtValue = null;
if (objValue.ToString() != "")
dtValue = Convert.ToDateTime(objValue);
p.SetValue(item, dtValue, null);
}
else if (p.PropertyType == typeof(Boolean?))
{
Boolean? bValue = null;
if (objValue.ToString() != "")
bValue = Convert.ToBoolean(objValue);
p.SetValue(item, bValue, null);
}
else if (p.PropertyType == typeof(Decimal?))
{
Decimal? decValue = null;
if (objValue.ToString() != "")
decValue = Convert.ToDecimal(objValue);
p.SetValue(item, decValue, null);
}
else if (p.PropertyType == typeof(Int32?) || p.PropertyType == typeof(Int32))
{
Int32? iValue = null;
if (objValue.ToString() != "")
iValue = Convert.ToInt32(objValue);
p.SetValue(item, iValue, null);
}
else if (p.PropertyType == typeof(Double?))
{
Double? dblValue = null;
if (objValue.ToString() != "")
dblValue = Convert.ToDouble(objValue);
p.SetValue(item, dblValue, null);
}
else
p.SetValue(item, objValue.ToString(), null);
iColIndex++;
}
return item;
}
/// <summary>
/// Converts a list of DataRow to a list of something else.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <returns></returns>
public static List<T> ConvertTo<T>(this List<DataRow> list)
{
List<T> result = (List<T>)Activator.CreateInstance<List<T>>();
list.ForEach(rec =>
{
result.Add(rec.ConvertTo<T>());
});
return result;
}
}
public static class StringExtensions
{
/// <summary>
/// Returns TRUE if both are equal or if one contains the other, returns FALSE for nulls/blanks
/// </summary>
public static bool IsEqualOrPartiallyMatchedTo( this string strMain, string strCompareTo )
{
if( strCompareTo == null ) return false;
if( strMain == null ) return false;
string strMainLower = strMain.ToLower();
string strCompareToLower = strCompareTo.ToLower();
if( strMainLower.Equals( "" ) || strCompareToLower.Equals( "" ) )
return false;
if( strMainLower.Equals( strCompareToLower )
|| strMainLower.Contains( strCompareToLower )
|| strCompareToLower.Contains( strMainLower ) )
return true;
return false;
}
public static string Left( this string strMain, int iLimit )
{
if( strMain.Length > iLimit )
return strMain.Substring( 0, iLimit );
return strMain;
}
public static bool IsMetaphoneMatchedTo( this string strMain, string strCompareTo )
{
if( strCompareTo == null ) return false;
if( strMain == null ) return false;
string strMainNbrs = Util.GetNumbersInString( strMain );
string strCompareToNbrs = Util.GetNumbersInString( strCompareTo );
//string strMPMain = string.Concat( strMainNbrs, Util.Metaphone( strMain ) );
//string strMPCompareTo = string.Concat( strCompareToNbrs, Util.Metaphone( strCompareTo ) );
//// attempt to match metaphone
//if( strMPMain.Equals( strMPCompareTo ) )
// return true;
// if they didn't match, try again after more treatment
string strCompareToKey = string.Concat( strMainNbrs, Util.NormalizeForMatching( strCompareTo ) );
string strMainKey = string.Concat( strCompareToNbrs, Util.NormalizeForMatching( strMain ) );
if( strMainKey.Equals( strCompareToKey ) )
return true;
return false;
}
/// <summary>
/// Returns Equals if both are not null/blank, if either or both are null returns TRUE. It is a "relaxed" Equals
/// </summary>
public static bool NotNullBlankAndEquals( this string strMain, string strCompareTo )
{
if( strMain == null || strCompareTo == null ) return false;
if( strMain.Trim().Equals( "" ) || strCompareTo.Trim().Equals( "" ) ) return false;
return strMain.Equals( strCompareTo );
}
/// <summary>
/// Returns Equals if both datetimes are not null, if either or both are null returns TRUE. It is a "relaxed" Equals
/// </summary>
public static bool NotNullAndEquals( this DateTime? dtMain, DateTime? dtCompareTo )
{
if( dtMain == null && dtCompareTo == null ) return false;
if( dtMain != null && dtCompareTo == null ) return false;
if( dtMain == null && dtCompareTo != null ) return false;
DateTime dt1 = (DateTime) dtMain, dt2 = (DateTime) dtCompareTo;
return dt1.CompareTo( dt2 ) == 0;
}
/// <summary>
/// Returns Equals if both are not null, if either or both are null returns TRUE. It is a "relaxed" Equals
/// </summary>
public static bool NotNullAndEquals<T>( this T strMain, T strCompareTo )
{
if( strMain == null && strCompareTo == null ) return false;
if( strMain != null && strCompareTo == null ) return false;
if( strMain == null && strCompareTo != null ) return false;
return strMain.Equals( strCompareTo );
}
/// <summary>
/// Returns Equals if both are not null, returns TRUE if both are null, otherwise returns FALSE
/// </summary>
public static bool NullAwareEquals( this string strMain, string strCompareTo )
{
//if( strMain.Trim().Equals( "" ) || strCompareTo.Trim().Equals( "" ) ) return true;
if( strMain == null && strCompareTo == null ) return true;
if( strMain != null && strCompareTo == null ) return false;
if( strMain == null && strCompareTo != null ) return false;
return strMain.Equals( strCompareTo );
}
/// <summary>
/// Returns Equals if both are not null, returns TRUE if both are null, otherwise returns FALSE
/// </summary>
public static bool NullAwareEquals<T>( this T strMain, T strCompareTo )
{
if( strMain == null && strCompareTo == null ) return true;
if( strMain != null && strCompareTo == null ) return false;
if( strMain == null && strCompareTo != null ) return false;
return strMain.Equals( strCompareTo );
}
public static bool ContainsAnyPartOf( this string strList2Exclude, string strValue )
{
string[] strList = strList2Exclude != null ? strList2Exclude.Split( new char[] { '|' } ) : new string[] {};
foreach( string strExclude in strList )
{
if( strValue.Contains( strExclude ) )
return true;
}
return false;
}
public static string ParseFromTo( this string strValue, string strFrom, string strTo )
{
int iPos = strValue.IndexOf( strFrom ) + strFrom.Length;
int iPosNext = strValue.IndexOf( strTo );
string strResult = strValue.Substring( iPos, iPosNext - iPos );
return strResult;
}
}
public static class DataExtensions
{
public static string COLS_TO_EXCLUDE = "Account|Attachments|CreatedBy|CreatedDate|FeedSubscriptionsForEntity|IsDeleted|IsDeletedSpecified|LastModifiedBy|LastModifiedDate|LastModifiedDateSpecified|Notes|NotesAndAttachments|ProcessInstances|ProcessSteps|SystemModstamp|SystemModstampSpecified|fieldsToNull|__cSpecified";
/// <summary>
/// Checks if object is a blank or null string (more intelligible/faster this way)
/// </summary>
public static bool IsNullOrBlank( this string obj )
{
return ( obj == null || obj.Trim().Length == 0 );
}
/// <summary>
/// Checks if object is a blank or null string (more intelligible/faster this way)
/// </summary>
public static bool IsNullOrBlank( this object obj )
{
return ( obj == null || obj.ToString().Length == 0 );
}
/// <summary>
/// Checks if object is a blank or null string (more intelligible/faster this way)
/// </summary>
public static bool IsNullOrBlank<T>( this T obj )
{
return ( obj == null || obj.ToString().Length == 0 );
}
/// <summary>
/// Creates a tab delimited string with the values of the DataRow
/// </summary>
public static string ToTabString( this DataRow objDR )
{
StringBuilder strbResult = new StringBuilder( objDR.Table.Columns.Count * 15 );
foreach( DataColumn objDC in objDR.Table.Columns )
{
strbResult.Append( "\t" );
strbResult.Append( ( objDR[ objDC ] != null ) ? objDR[ objDC ].ToString() : "" );
}
// remove 1st tab
strbResult.Remove( 0, 1 );
return strbResult.ToString();
}
/// <summary>
/// Creates a tab delimited string with a list of the DataTable column names
/// </summary>
public static string ColumnsToTabString(this DataTable objDT)