-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGenericParserAdapter.cs
More file actions
440 lines (383 loc) · 17.7 KB
/
GenericParserAdapter.cs
File metadata and controls
440 lines (383 loc) · 17.7 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
// GenericParsing
// Copyright © 2010 Andrew Rissing
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#region Using Directives
using System;
using System.Data;
using System.IO;
using System.Text;
using System.Xml;
#endregion Using Directives
namespace GenericParsing
{
/// <summary>
/// The <see cref="GenericParserAdapter"/> is used to modify the <see cref="GenericParser"/>
/// to allow it parse a file and place them into various formats.
/// </summary>
/// <threadsafety static="false" instance="false"/>
public class GenericParserAdapter : GenericParser
{
#region Constants
/// <summary>
/// Defines the default value for including the file line number (false).
/// </summary>
public const bool DefaultIncludeFileLineNumber = false;
/// <summary>
/// Defines the number of skip ending data rows (0).
/// </summary>
public const int DefaultSkipEndingDataRows = 0;
private const string XML_INCLUDE_FILE_LINE_NUMBER = "IncludeFileLineNumber";
private const string XML_SKIP_ENDING_DATA_ROWS = "SkipEndingDataRows";
private const string FILE_LINE_NUMBER = "FileLineNumber";
#endregion Constants
#region Static Code
/// <summary>
/// Adds a column name to the given <see cref="DataTable"/>, such that
/// it ensures a unique column name.
/// </summary>
/// <param name="dtData">The <see cref="DataTable"/> to add the column to.</param>
/// <param name="strColumnName">The desired column name to add.</param>
private static void AddColumnToTable(DataTable dtData, string strColumnName)
{
if (strColumnName != null)
{
if (dtData.Columns[strColumnName] == null)
dtData.Columns.Add(strColumnName);
else
{
string strNewColumnName;
int intCount = 0;
// Looks like we need to generate a new column name.
do
{
strNewColumnName = string.Format("{0}{1}", strColumnName, ++intCount);
}
while (dtData.Columns[strNewColumnName] != null);
dtData.Columns.Add(strNewColumnName);
}
}
else
dtData.Columns.Add();
}
#endregion Static Code
#region Constructors
/// <summary>
/// Constructs an instance of a <see cref="GenericParserAdapter"/>
/// with the default settings.
/// </summary>
/// <remarks>
/// When using this constructor, the datasource must be set prior to using the parser
/// (using <see cref="GenericParser.SetDataSource(string)"/>), otherwise an exception will be thrown.
/// </remarks>
public GenericParserAdapter()
: base()
{
this.IncludeFileLineNumber = GenericParserAdapter.DefaultIncludeFileLineNumber;
this.SkipEndingDataRows = GenericParserAdapter.DefaultSkipEndingDataRows;
}
/// <summary>
/// Constructs an instance of a <see cref="GenericParserAdapter"/> and sets
/// the initial datasource as the file referenced by the string passed in.
/// </summary>
/// <param name="strFileName">The file name to set as the initial datasource.</param>
public GenericParserAdapter(string strFileName)
: this()
{
this.SetDataSource(strFileName);
}
/// <summary>
/// Constructs an instance of a <see cref="GenericParserAdapter"/> and sets
/// the initial datasource as the file referenced by the string passed in with
/// the provided encoding.
/// </summary>
/// <param name="strFileName">The file name to set as the initial datasource.</param>
/// <param name="encoding">The <see cref="Encoding"/> of the file being referenced.</param>
public GenericParserAdapter(string strFileName, Encoding encoding)
: this()
{
this.SetDataSource(strFileName, encoding);
}
/// <summary>
/// Constructs an instance of a <see cref="GenericParserAdapter"/> and sets
/// the initial datasource as the <see cref="TextReader"/> passed in.
/// </summary>
/// <param name="txtReader">
/// The <see cref="TextReader"/> containing the data to be parsed.
/// </param>
public GenericParserAdapter(TextReader txtReader)
: this()
{
this.SetDataSource(txtReader);
}
#endregion Constructors
#region Public Code
/// <summary>
/// Gets or sets whether or not the <see cref="GenericParser.FileRowNumber"/> from where
/// the data was retrieved should be included as part of the result set.
/// </summary>
/// <remarks>
/// <para>
/// Default: <see langword="false"/>
/// </para>
/// <para>
/// If parsing has started, this value cannot be updated.
/// </para>
/// </remarks>
/// <exception cref="InvalidOperationException">Attempting to modify the configuration, while parsing.</exception>
public bool IncludeFileLineNumber
{
get
{
return this.m_blnIncludeFileLineNumber;
}
set
{
if (this.m_ParserState == ParserState.Parsing)
throw new InvalidOperationException("Parsing has already begun, close the existing parse first.");
this.m_blnIncludeFileLineNumber = value;
}
}
/// <summary>
/// Gets or sets the number of rows of data to ignore at the end of the file.
/// </summary>
/// <value>The number of data rows to skip at the end of the datasource</value>
/// <remarks>
/// <para>
/// A value of zero will ensure no rows are ignored.
/// </para>
/// <para>
/// Default: 0
/// </para>
/// <para>
/// If parsing has started, this value cannot be updated.
/// </para>
/// </remarks>
/// <exception cref="InvalidOperationException">Attempting to modify the configuration, while parsing.</exception>
public int SkipEndingDataRows
{
get
{
return this.m_intSkipEndingDataRows;
}
set
{
if (this.m_ParserState == ParserState.Parsing)
throw new InvalidOperationException("Parsing has already begun, close the existing parse first.");
this.m_intSkipEndingDataRows = value;
if (this.m_intSkipEndingDataRows < 0)
this.m_intSkipEndingDataRows = 0;
}
}
/// <summary>
/// Generates an <see cref="XmlDocument"/> based on the data stored within
/// the entire data source after it was parsed.
/// </summary>
/// <returns>
/// The <see cref="XmlDocument"/> containing all of the data in the data
/// source.
/// </returns>
/// <exception cref="InvalidOperationException">
/// Attempting to read without properly setting up the <see cref="GenericParserAdapter"/>.
/// </exception>
/// <exception cref="ParsingException">
/// Thrown in the situations where the <see cref="GenericParserAdapter"/> cannot continue
/// due to a conflict between the setup and the data being parsed.
/// </exception>
/// <example>
/// <code lang="C#" escaped="true">
/// using (GenericParserAdapter p = new GenericParserAdapter(@"C:\MyData.txt"))
/// XmlDocument xmlDoc = p.GetXml();
/// </code>
/// </example>
public XmlDocument GetXml()
{
DataSet dsData;
XmlDocument xmlDocument = null;
dsData = this.GetDataSet();
if (dsData != null)
{
xmlDocument = new XmlDocument();
xmlDocument.LoadXml(dsData.GetXml());
}
return xmlDocument;
}
/// <summary>
/// Generates a <see cref="DataSet"/> based on the data stored within
/// the entire data source after it was parsed.
/// </summary>
/// <returns>
/// The <see cref="DataSet"/> containing all of the data in the
/// data source.
/// </returns>
/// <exception cref="InvalidOperationException">
/// Attempting to read without properly setting up the <see cref="GenericParserAdapter"/>.
/// </exception>
/// <exception cref="ParsingException">
/// Thrown in the situations where the <see cref="GenericParserAdapter"/> cannot continue
/// due to a conflict between the setup and the data being parsed.
/// </exception>
/// <example>
/// <code lang="C#" escaped="true">
/// using (GenericParserAdapter p = new GenericParserAdapter(@"C:\MyData.txt"))
/// DataSet dsResults = p.GetDataSet();
/// </code>
/// </example>
public DataSet GetDataSet()
{
DataTable dtData;
DataSet dsData = null;
dtData = this.GetDataTable();
if (dtData != null)
{
dsData = new DataSet();
dsData.Tables.Add(dtData);
}
return dsData;
}
/// <summary>
/// Generates a <see cref="DataTable"/> based on the data stored within
/// the entire data source after it was parsed.
/// </summary>
/// <returns>
/// The <see cref="DataTable"/> containing all of the data in the data
/// source.
/// </returns>
/// <exception cref="InvalidOperationException">
/// Attempting to read without properly setting up the <see cref="GenericParserAdapter"/>.
/// </exception>
/// <exception cref="ParsingException">
/// Thrown in the situations where the <see cref="GenericParserAdapter"/> cannot continue
/// due to a conflict between the setup and the data being parsed.
/// </exception>
/// <example>
/// <code lang="C#" escaped="true">
/// using (GenericParserAdapter p = new GenericParserAdapter(@"C:\MyData.txt"))
/// DataTable dtResults = p.GetDataTable();
/// </code>
/// </example>
public DataTable GetDataTable()
{
DataRow drRow;
DataTable dtData;
int intCreatedColumns, intSkipRowsAtEnd;
dtData = new DataTable();
dtData.BeginLoadData();
intCreatedColumns = 0;
while (this.Read())
{
// See if we have the appropriate number of columns.
if (this.m_lstColumnNames.Count > intCreatedColumns)
{
// Add in our column to store off the file line number.
if (this.m_blnIncludeFileLineNumber && (intCreatedColumns < 1))
dtData.Columns.Add(GenericParserAdapter.FILE_LINE_NUMBER);
for (int intColumnIndex = intCreatedColumns; intColumnIndex < this.m_lstColumnNames.Count; ++intColumnIndex, ++intCreatedColumns)
GenericParserAdapter.AddColumnToTable(dtData, this.m_lstColumnNames[intColumnIndex]);
}
if (!this.IsCurrentRowEmpty || !this.SkipEmptyRows)
{
drRow = dtData.NewRow();
if (this.m_blnIncludeFileLineNumber)
{
drRow[0] = this.FileRowNumber;
// Now, add in the data retrieved from the current row.
for (int intColumnIndex = 0; intColumnIndex < this.m_lstData.Count; ++intColumnIndex)
drRow[intColumnIndex + 1] = this.m_lstData[intColumnIndex];
}
else
{
// Since we don't have to account for the row number, just place the value right into the data row.
drRow.ItemArray = this.m_lstData.ToArray();
}
dtData.Rows.Add(drRow);
}
}
intSkipRowsAtEnd = this.m_intSkipEndingDataRows;
// Remove any rows at the end that need to be skipped.
while ((intSkipRowsAtEnd-- > 0) && (dtData.Rows.Count > 0))
dtData.Rows.RemoveAt(dtData.Rows.Count - 1);
dtData.EndLoadData();
return dtData;
}
/// <summary>
/// Loads the base <see cref="GenericParser"/> class from the
/// <see cref="XmlDocument"/> and then retrieves additional information
/// from the Xml that is specific to the <see cref="GenericParserAdapter"/>.
/// </summary>
/// <param name="xmlConfig">
/// The <see cref="XmlDocument"/> containing the configuration information.
/// </param>
/// <exception cref="ArgumentException">In the event that the XmlConfig file contains a value that is invalid,
/// an <see cref="ArgumentException"/> could be thrown.</exception>
/// <exception cref="ArgumentNullException">In the event that the XmlConfig file contains a value that is invalid,
/// an <see cref="ArgumentNullException"/> could be thrown.</exception>
/// <exception cref="ArgumentOutOfRangeException">In the event that the XmlConfig file contains a value that is invalid,
/// an <see cref="ArgumentOutOfRangeException"/> could be thrown.</exception>
/// <exception cref="InvalidOperationException">Attempting to modify the configuration, while parsing.</exception>
public override void Load(XmlDocument xmlConfig)
{
XmlElement xmlElement;
// Load the base information for the GenericParser.
base.Load(xmlConfig);
// Initialize the value for the file line number.
this.m_blnIncludeFileLineNumber = GenericParserAdapter.DefaultIncludeFileLineNumber;
this.m_intSkipEndingDataRows = GenericParserAdapter.DefaultSkipEndingDataRows;
/////////////////////////////////////////////
// Load the rest of the information that's //
// specific to the GenericParserAdapter. //
/////////////////////////////////////////////
xmlElement = xmlConfig.DocumentElement[XML_INCLUDE_FILE_LINE_NUMBER];
if ((xmlElement != null) && (xmlElement.InnerText != null))
this.IncludeFileLineNumber = Convert.ToBoolean(xmlElement.InnerText);
/////////////////////////////////////////////////////////////
xmlElement = xmlConfig.DocumentElement[XML_SKIP_ENDING_DATA_ROWS];
if ((xmlElement != null) && (xmlElement.InnerText != null))
this.SkipEndingDataRows = Convert.ToInt32(xmlElement.InnerText);
}
/// <summary>
/// Saves the configuration of the <see cref="GenericParserAdapter"/>
/// to an <see cref="XmlDocument"/>.
/// </summary>
/// <returns>
/// The <see cref="XmlDocument"/> that will store the configuration
/// information of the current setup of the <see cref="GenericParserAdapter"/>.
/// </returns>
public override XmlDocument Save()
{
XmlDocument xmlConfig = base.Save();
XmlElement xmlElement;
///////////////////////////////////////////////////////////////
// Take the document and insert the additional configuration //
// specific to the GenericParserAdapter. //
///////////////////////////////////////////////////////////////
xmlElement = xmlConfig.CreateElement(XML_INCLUDE_FILE_LINE_NUMBER);
xmlElement.InnerText = this.IncludeFileLineNumber.ToString();
xmlConfig.DocumentElement.AppendChild(xmlElement);
/////////////////////////////////////////////////////////////
xmlElement = xmlConfig.CreateElement(XML_SKIP_ENDING_DATA_ROWS);
xmlElement.InnerText = this.m_intSkipEndingDataRows.ToString();
xmlConfig.DocumentElement.AppendChild(xmlElement);
return xmlConfig;
}
#endregion Public Code
#region Private Code
private bool m_blnIncludeFileLineNumber;
private int m_intSkipEndingDataRows;
#endregion Private Code
}
}