Advertisement
LaughingMan

Untitled

Dec 9th, 2015
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.36 KB | None | 0 0
  1. private static void ProcessCSIDataFile(ref CSIDataRecord record, string[] rows)
  2.         {
  3.             var headers = rows.First().SplitCSV().ToArray();
  4.  
  5.             var recordRows = rows.Skip(1);
  6.  
  7.             foreach (var row in recordRows)
  8.             {
  9.                 var dataRecord = new CSIDataCSVRecord();
  10.                 var columns = row.SplitCSV().ToArray();
  11.  
  12.                 if (columns.Length != headers.Length)
  13.                     continue;
  14.  
  15.                 for (var i = 0; i < headers.Length; i++)
  16.                 {
  17.                     var prop = dataRecord.GetType().GetProperty(headers[i], BindingFlags.Public | BindingFlags.Instance);
  18.  
  19.                     if (prop != null && prop.CanWrite && !columns[i].IsNullOrWhiteSpace())
  20.                     {
  21.                         var value = columns[i].Trim();
  22.                         var length = value.Length;
  23.  
  24.                         if (maxLengths.ContainsKey(prop.Name))
  25.                         {
  26.                             if (maxLengths[prop.Name] < length)
  27.                                 maxLengths[prop.Name] = length;
  28.                         }
  29.                         else
  30.                         {
  31.                             maxLengths.Add(prop.Name, length);
  32.                         }
  33.  
  34.                         if (value.IsNullOrWhiteSpace())
  35.                             continue;
  36.  
  37.                         var t = Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType;
  38.  
  39.                         // CSI Data has 0 and 1 for false and true values
  40.                         // Normally not needed but is in this circumstance
  41.                         if (t == typeof(bool))
  42.                             value = (value != "0" && value.ToLower() != "false").ToString();
  43.  
  44.                         // CSI Data may include scientific notation in decimals.
  45.                         // We need to make sure all decimals are clean before parsing
  46.                         if (t == typeof(decimal))
  47.                             value = decimal.Parse(value, NumberStyles.Any).ToString(CultureInfo.InvariantCulture);
  48.  
  49.                         var safeValue = Convert.ChangeType(value, t, CultureInfo.InvariantCulture);
  50.                         prop.SetValue(dataRecord, safeValue, null);
  51.                     }
  52.                 }
  53.                 record.CSIDataCSVRecords.Add(dataRecord);
  54.             }
  55.         }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement