This repository has been archived by the owner on Dec 24, 2022. It is now read-only.
/
CsvReader.cs
411 lines (331 loc) · 13.2 KB
/
CsvReader.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
using System;
using System.Collections.Generic;
using System.Linq;
using ServiceStack.Text.Common;
using ServiceStack.Text.Jsv;
namespace ServiceStack.Text
{
public class CsvReader
{
public static List<string> ParseLines(string csv)
{
var rows = new List<string>();
if (string.IsNullOrEmpty(csv))
return rows;
var withinQuotes = false;
var lastPos = 0;
var i = -1;
var len = csv.Length;
while (++i < len)
{
var c = csv[i];
if (c == JsWriter.QuoteChar)
{
var isLiteralQuote = i + 1 < len && csv[i + 1] == JsWriter.QuoteChar;
if (isLiteralQuote)
{
i++;
continue;
}
withinQuotes = !withinQuotes;
}
if (withinQuotes)
continue;
if (c == JsWriter.LineFeedChar)
{
var str = i > 0 && csv[i - 1] == JsWriter.ReturnChar
? csv.Substring(lastPos, i - lastPos - 1)
: csv.Substring(lastPos, i - lastPos);
if (str.Length > 0)
rows.Add(str);
lastPos = i + 1;
}
}
if (i > lastPos)
{
var str = csv.Substring(lastPos, i - lastPos);
if (str.Length > 0)
rows.Add(str);
}
return rows;
}
public static List<string> ParseFields(string line) => ParseFields(line, null);
public static List<string> ParseFields(string line, Func<string,string> parseFn)
{
var to = new List<string>();
if (string.IsNullOrEmpty(line))
return to;
var i = -1;
var len = line.Length;
while (++i <= len)
{
var value = EatValue(line, ref i);
to.Add(parseFn != null ? parseFn(value.FromCsvField()) : value.FromCsvField());
}
return to;
}
//Originally from JsvTypeSerializer.EatValue()
public static string EatValue(string value, ref int i)
{
var tokenStartPos = i;
var valueLength = value.Length;
if (i == valueLength) return null;
var valueChar = value[i];
var withinQuotes = false;
var endsToEat = 1;
var itemSeperator = CsvConfig.ItemSeperatorString.Length == 1
? CsvConfig.ItemSeperatorString[0]
: JsWriter.ItemSeperator;
if (valueChar == itemSeperator || valueChar == JsWriter.MapEndChar)
return null;
if (valueChar == JsWriter.QuoteChar) //Is Within Quotes, i.e. "..."
{
while (++i < valueLength)
{
valueChar = value[i];
if (valueChar != JsWriter.QuoteChar) continue;
var isLiteralQuote = i + 1 < valueLength && value[i + 1] == JsWriter.QuoteChar;
i++; //skip quote
if (!isLiteralQuote)
break;
}
return value.Substring(tokenStartPos, i - tokenStartPos);
}
if (valueChar == JsWriter.MapStartChar) //Is Type/Map, i.e. {...}
{
while (++i < valueLength && endsToEat > 0)
{
valueChar = value[i];
if (valueChar == JsWriter.QuoteChar)
withinQuotes = !withinQuotes;
if (withinQuotes)
continue;
if (valueChar == JsWriter.MapStartChar)
endsToEat++;
if (valueChar == JsWriter.MapEndChar)
endsToEat--;
}
if (endsToEat > 0)
{
//Unmatched start and end char, give up
i = tokenStartPos;
valueChar = value[i];
}
else
return value.Substring(tokenStartPos, i - tokenStartPos);
}
if (valueChar == JsWriter.ListStartChar) //Is List, i.e. [...]
{
while (++i < valueLength && endsToEat > 0)
{
valueChar = value[i];
if (valueChar == JsWriter.QuoteChar)
withinQuotes = !withinQuotes;
if (withinQuotes)
continue;
if (valueChar == JsWriter.ListStartChar)
endsToEat++;
if (valueChar == JsWriter.ListEndChar)
endsToEat--;
}
if (endsToEat > 0)
{
//Unmatched start and end char, give up
i = tokenStartPos;
valueChar = value[i];
}
else
return value.Substring(tokenStartPos, i - tokenStartPos);
}
//if value starts with MapStartChar, check MapEndChar to terminate
char specEndChar = itemSeperator;
if (value[tokenStartPos] == JsWriter.MapStartChar)
specEndChar = JsWriter.MapEndChar;
while (++i < valueLength) //Is Value
{
valueChar = value[i];
if (valueChar == itemSeperator || valueChar == specEndChar)
{
break;
}
}
return value.Substring(tokenStartPos, i - tokenStartPos);
}
}
public class CsvReader<T>
{
public static List<string> Headers { get; set; }
internal static List<SetMemberDelegate<T>> PropertySetters;
internal static Dictionary<string, SetMemberDelegate<T>> PropertySettersMap;
internal static List<ParseStringDelegate> PropertyConverters;
internal static Dictionary<string, ParseStringDelegate> PropertyConvertersMap;
static CsvReader()
{
Reset();
}
internal static void Reset()
{
Headers = new List<string>();
PropertySetters = new List<SetMemberDelegate<T>>();
PropertySettersMap = new Dictionary<string, SetMemberDelegate<T>>(PclExport.Instance.InvariantComparerIgnoreCase);
PropertyConverters = new List<ParseStringDelegate>();
PropertyConvertersMap = new Dictionary<string, ParseStringDelegate>(PclExport.Instance.InvariantComparerIgnoreCase);
foreach (var propertyInfo in TypeConfig<T>.Properties)
{
if (!propertyInfo.CanWrite || propertyInfo.GetSetMethod(nonPublic:true) == null) continue;
if (!TypeSerializer.CanCreateFromString(propertyInfo.PropertyType)) continue;
var propertyName = propertyInfo.Name;
var setter = propertyInfo.CreateSetter<T>();
PropertySetters.Add(setter);
var converter = JsvReader.GetParseFn(propertyInfo.PropertyType);
PropertyConverters.Add(converter);
var dcsDataMemberName = propertyInfo.GetDataMemberName();
if (dcsDataMemberName != null)
propertyName = dcsDataMemberName;
Headers.Add(propertyName);
PropertySettersMap[propertyName] = setter;
PropertyConvertersMap[propertyName] = converter;
}
}
internal static void ConfigureCustomHeaders(Dictionary<string, string> customHeadersMap)
{
Reset();
for (var i = Headers.Count - 1; i >= 0; i--)
{
var oldHeader = Headers[i];
if (!customHeadersMap.TryGetValue(oldHeader, out var newHeader))
{
Headers.RemoveAt(i);
PropertySetters.RemoveAt(i);
}
else
{
Headers[i] = newHeader;
PropertySettersMap.TryGetValue(oldHeader, out var setter);
PropertySettersMap.Remove(oldHeader);
PropertySettersMap[newHeader] = setter;
PropertyConvertersMap.TryGetValue(oldHeader, out var converter);
PropertyConvertersMap.Remove(oldHeader);
PropertyConvertersMap[newHeader] = converter;
}
}
}
private static List<T> GetSingleRow(IEnumerable<string> rows, Type recordType)
{
var row = new List<T>();
foreach (var value in rows)
{
var to = recordType == typeof(string)
? (T)(object)value
: TypeSerializer.DeserializeFromString<T>(value);
row.Add(to);
}
return row;
}
public static List<T> GetRows(IEnumerable<string> records)
{
var rows = new List<T>();
if (records == null) return rows;
if (typeof(T).IsValueType || typeof(T) == typeof(string))
{
return GetSingleRow(records, typeof(T));
}
foreach (var record in records)
{
var to = typeof(T).CreateInstance<T>();
foreach (var propertySetter in PropertySetters)
{
propertySetter(to, record);
}
rows.Add(to);
}
return rows;
}
public static object ReadObject(string csv)
{
if (csv == null) return null; //AOT
return Read(CsvReader.ParseLines(csv));
}
public static object ReadObjectRow(string csv)
{
if (csv == null) return null; //AOT
return ReadRow(csv);
}
public static List<Dictionary<string, string>> ReadStringDictionary(IEnumerable<string> rows)
{
if (rows == null) return null; //AOT
var to = new List<Dictionary<string, string>>();
List<string> headers = null;
foreach (var row in rows)
{
if (headers == null)
{
headers = CsvReader.ParseFields(row);
continue;
}
var values = CsvReader.ParseFields(row);
var map = new Dictionary<string, string>();
for (int i = 0; i < headers.Count; i++)
{
var header = headers[i];
map[header] = values[i];
}
to.Add(map);
}
return to;
}
public static List<T> Read(List<string> rows)
{
var to = new List<T>();
if (rows == null || rows.Count == 0) return to; //AOT
if (typeof(T).IsAssignableFrom(typeof(Dictionary<string, string>)))
{
return ReadStringDictionary(rows).ConvertAll(x => (T)(object)x);
}
if (typeof(T).IsAssignableFrom(typeof(List<string>)))
{
return new List<T>(rows.Select(x => (T)(object)CsvReader.ParseFields(x)));
}
List<string> headers = null;
if (!CsvConfig<T>.OmitHeaders || Headers.Count == 0)
{
headers = CsvReader.ParseFields(rows[0], s => s.Trim());
}
if (typeof(T).IsValueType || typeof(T) == typeof(string))
{
return rows.Count == 1
? GetSingleRow(CsvReader.ParseFields(rows[0]), typeof(T))
: GetSingleRow(rows, typeof(T));
}
for (var rowIndex = headers == null ? 0 : 1; rowIndex < rows.Count; rowIndex++)
{
var row = rows[rowIndex];
var o = typeof(T).CreateInstance<T>();
var fields = CsvReader.ParseFields(row);
for (int i = 0; i < fields.Count; i++)
{
var setter = i < PropertySetters.Count ? PropertySetters[i] : null;
if (headers != null)
PropertySettersMap.TryGetValue(headers[i], out setter);
if (setter == null)
continue;
var converter = i < PropertyConverters.Count ? PropertyConverters[i] : null;
if (headers != null)
PropertyConvertersMap.TryGetValue(headers[i], out converter);
if (converter == null)
continue;
var field = fields[i];
var convertedValue = converter(field);
setter(o, convertedValue);
}
to.Add(o);
}
return to;
}
public static T ReadRow(string value)
{
if (value == null) return default(T); //AOT
return Read(CsvReader.ParseLines(value)).FirstOrDefault();
}
}
}