finished config activity, switched to new CSV parser

This commit is contained in:
mgroves 2011-02-26 10:13:52 -05:00
parent 348a999912
commit fd63359e48
92 changed files with 4792 additions and 7195 deletions

View file

@ -1,37 +0,0 @@
#region " © Copyright 2005-07 to Marcos Meli - http://www.marcosmeli.com.ar"
// Errors, suggestions, contributions, send a mail to: marcos@filehelpers.com.
#endregion
using System;
namespace FileHelpers
{
/// <summary>Allow to declarative set what records must be included or excluded when reading.</summary>
/// <remarks>See the <a href="attributes.html">Complete Attributes List</a> for more clear info and examples of each one.</remarks>
/// <seealso href="attributes.html">Attributes List</seealso>
/// <seealso href="quick_start.html">Quick Start Guide</seealso>
/// <seealso href="examples.html">Examples of Use</seealso>
[AttributeUsage(AttributeTargets.Class)]
public sealed class ConditionalRecordAttribute : Attribute
{
internal RecordCondition mCondition;
internal string mConditionSelector;
/// <summary>Allow to declarative show what records must be included or excluded</summary>
/// <param name="condition">The condition used to include or exclude each record</param>
/// <param name="selector">The selector for the condition.</param>
public ConditionalRecordAttribute(RecordCondition condition, string selector)
{
if (selector == null || selector.Length == 0)
throw new BadUsageException("The selector arg for the ConditionalRecordAttribute can't be null or empty.");
mCondition = condition;
mConditionSelector = selector;
}
}
}

View file

@ -1,33 +0,0 @@
#region " © Copyright 2005-07 to Marcos Meli - http://www.marcosmeli.com.ar"
// Errors, suggestions, contributions, send a mail to: marcos@filehelpers.com.
#endregion
using System;
namespace FileHelpers
{
/// <summary>Indicates that this class represents a delimited record. </summary>
/// <remarks>See the <a href="attributes.html">Complete Attributes List</a> for more clear info and examples of each one.</remarks>
/// <seealso href="attributes.html">Attributes List</seealso>
/// <seealso href="quick_start.html">Quick Start Guide</seealso>
/// <seealso href="examples.html">Examples of Use</seealso>
[AttributeUsage(AttributeTargets.Class)]
public sealed class DelimitedRecordAttribute : TypedRecordAttribute
{
internal string Separator;
/// <summary>Indicates that this class represents a delimited record. </summary>
/// <param name="delimiter">The separator string used to split the fields of the record.</param>
public DelimitedRecordAttribute(string delimiter)
{
if (Separator != String.Empty)
this.Separator = delimiter;
else
throw new ArgumentException("sep debe ser <> \"\"");
}
}
}

View file

@ -1,44 +0,0 @@
#region " © Copyright 2005-07 to Marcos Meli - http://www.marcosmeli.com.ar"
// Errors, suggestions, contributions, send a mail to: marcos@filehelpers.com.
#endregion
using System;
namespace FileHelpers
{
/// <summary>Indicates the <see cref="AlignMode"/> used for <b>write</b> operations.</summary>
/// <remarks>See the <a href="attributes.html">Complete Attributes List</a> for more clear info and examples of each one.</remarks>
/// <seealso href="attributes.html">Attributes List</seealso>
/// <seealso href="quick_start.html">Quick Start Guide</seealso>
/// <seealso href="examples.html">Examples of Use</seealso>
[AttributeUsage(AttributeTargets.Field)]
public sealed class FieldAlignAttribute : Attribute
{
#region " Constructors "
/// <summary>Uses the ' ' char to align.</summary>
/// <param name="align">The position of the alignment.</param>
public FieldAlignAttribute(AlignMode align) : this(align, ' ')
{
}
/// <summary>You can indicate the align char.</summary>
/// <param name="align">The position of the alignment.</param>
/// <param name="alignChar">The character used to align.</param>
public FieldAlignAttribute(AlignMode align, char alignChar)
{
Align = align;
AlignChar = alignChar;
}
#endregion
/// <summary>The position of the alignment.</summary>
internal AlignMode Align;
/// <summary>The character used to align.</summary>
internal char AlignChar;
}
}

View file

@ -1,26 +0,0 @@
#region " © Copyright 2005-07 to Marcos Meli - http://www.marcosmeli.com.ar"
// Errors, suggestions, contributions, send a mail to: marcos@filehelpers.com.
#endregion
using System;
using System.ComponentModel;
namespace FileHelpers
{
/// <summary>Base class of <see cref="FieldFixedLengthAttribute"/> and <see cref="FieldDelimiterAttribute"/></summary>
/// <remarks>See the <a href="attributes.html">Complete Attributes List</a> for more clear info and examples of each one.</remarks>
/// <seealso href="attributes.html">Attributes List</seealso>
/// <seealso href="quick_start.html">Quick Start Guide</seealso>
/// <seealso href="examples.html">Examples of Use</seealso>
[AttributeUsage(AttributeTargets.Field)]
[EditorBrowsable(EditorBrowsableState.Never)]
public abstract class FieldAttribute : Attribute
{
/// <summary>Abstract class, see the inheritors.</summary>
protected FieldAttribute()
{
}
}
}

View file

@ -1,297 +0,0 @@
#region " © Copyright 2005-07 to Marcos Meli - http://www.marcosmeli.com.ar"
// Errors, suggestions, contributions, send a mail to: marcos@filehelpers.com.
#endregion
using System;
using System.Reflection;
using System.Text;
namespace FileHelpers
{
/// <summary>Indicates the <see cref="ConverterKind"/> used for read/write operations.</summary>
/// <remarks>See the <a href="attributes.html">Complete Attributes List</a> for more clear info and examples of each one.</remarks>
/// <seealso href="attributes.html">Attributes List</seealso>
/// <seealso href="quick_start.html">Quick Start Guide</seealso>
/// <seealso href="examples.html">Examples of Use</seealso>
[AttributeUsage(AttributeTargets.Field)]
public sealed class FieldConverterAttribute : Attribute
{
#region " Constructors "
/// <summary>Indicates the <see cref="ConverterKind"/> used for read/write ops. </summary>
/// <param name="converter">The <see cref="ConverterKind"/> used for the transformations.</param>
public FieldConverterAttribute(ConverterKind converter) : this(converter, new string[] {})
{
}
/// <summary>Indicates the <see cref="ConverterKind"/> used for read/write ops. </summary>
/// <param name="converter">The <see cref="ConverterKind"/> used for the transformations.</param>
/// <param name="arg1">The first param pased directly to the Converter Constructor.</param>
public FieldConverterAttribute(ConverterKind converter, string arg1) : this(converter, new string[] {arg1})
{
}
/// <summary>Indicates the <see cref="ConverterKind"/> used for read/write ops. </summary>
/// <param name="converter">The <see cref="ConverterKind"/> used for the transformations.</param>
/// <param name="arg1">The first param pased directly to the Converter Constructor.</param>
/// <param name="arg2">The second param pased directly to the Converter Constructor.</param>
public FieldConverterAttribute(ConverterKind converter, string arg1, string arg2)
: this(converter, new string[] {arg1, arg2})
{
}
/// <summary>Indicates the <see cref="ConverterKind"/> used for read/write ops. </summary>
/// <param name="converter">The <see cref="ConverterKind"/> used for the transformations.</param>
/// <param name="arg1">The first param pased directly to the Converter Constructor.</param>
/// <param name="arg2">The second param pased directly to the Converter Constructor.</param>
/// <param name="arg3">The third param pased directly to the Converter Constructor.</param>
public FieldConverterAttribute(ConverterKind converter, string arg1, string arg2, string arg3)
: this(converter, new string[] {arg1, arg2, arg3})
{
}
private FieldConverterAttribute(ConverterKind converter, params string[] args)
{
Kind = converter;
Type convType;
switch (converter)
{
case ConverterKind.Date:
convType = typeof (ConvertHelpers.DateTimeConverter);
break;
case ConverterKind.Byte:
convType = typeof (ConvertHelpers.ByteConverter);
break;
case ConverterKind.SByte:
convType = typeof(ConvertHelpers.SByteConverter);
break;
case ConverterKind.Int16:
convType = typeof (ConvertHelpers.Int16Converter);
break;
case ConverterKind.Int32:
convType = typeof (ConvertHelpers.Int32Converter);
break;
case ConverterKind.Int64:
convType = typeof (ConvertHelpers.Int64Converter);
break;
case ConverterKind.UInt16:
convType = typeof(ConvertHelpers.UInt16Converter);
break;
case ConverterKind.UInt32:
convType = typeof(ConvertHelpers.UInt32Converter);
break;
case ConverterKind.UInt64:
convType = typeof(ConvertHelpers.UInt64Converter);
break;
case ConverterKind.Decimal:
convType = typeof (ConvertHelpers.DecimalConverter);
break;
case ConverterKind.Double:
convType = typeof (ConvertHelpers.DoubleConverter);
break;
case ConverterKind.Single:
convType = typeof (ConvertHelpers.SingleConverter);
break;
case ConverterKind.Boolean:
convType = typeof (ConvertHelpers.BooleanConverter);
break;
default:
throw new BadUsageException("Converter '" + converter.ToString() + "' not found, you must specify a valid converter.");
}
//mType = type;
CreateConverter(convType, args);
}
/// <summary>Indicates the <see cref="ConverterKind"/> used for read/write ops. </summary>
/// <param name="customConverter">The Type of your custom converter.</param>
/// <param name="arg1">The first param pased directly to the Converter Constructor.</param>
public FieldConverterAttribute(Type customConverter, string arg1) : this(customConverter, new string[] {arg1})
{
}
/// <summary>Indicates the <see cref="ConverterKind"/> used for read/write ops. </summary>
/// <param name="customConverter">The Type of your custom converter.</param>
/// <param name="arg1">The first param pased directly to the Converter Constructor.</param>
/// <param name="arg2">The second param pased directly to the Converter Constructor.</param>
public FieldConverterAttribute(Type customConverter, string arg1, string arg2)
: this(customConverter, new string[] {arg1, arg2})
{
}
/// <summary>Indicates the <see cref="ConverterKind"/> used for read/write ops. </summary>
/// <param name="customConverter">The Type of your custom converter.</param>
/// <param name="arg1">The first param pased directly to the Converter Constructor.</param>
/// <param name="arg2">The second param pased directly to the Converter Constructor.</param>
/// <param name="arg3">The third param pased directly to the Converter Constructor.</param>
public FieldConverterAttribute(Type customConverter, string arg1, string arg2, string arg3)
: this(customConverter, new string[] {arg1, arg2, arg3})
{
}
/// <summary>Indicates a custom <see cref="ConverterBase"/> implementation.</summary>
/// <param name="customConverter">The Type of your custom converter.</param>
/// <param name="args">A list of params pased directly to your converter constructor.</param>
public FieldConverterAttribute(Type customConverter, params object[] args)
{
CreateConverter(customConverter, args);
}
/// <summary>Indicates a custom <see cref="ConverterBase"/> implementation.</summary>
/// <param name="customConverter">The Type of your custom converter.</param>
public FieldConverterAttribute(Type customConverter)
{
CreateConverter(customConverter, new object[] {});
}
#endregion
#region " Converter "
internal ConverterBase Converter;
internal ConverterKind Kind;
#endregion
#region " CreateConverter "
private void CreateConverter(Type convType, object[] args)
{
if (typeof (ConverterBase).IsAssignableFrom(convType))
{
ConstructorInfo constructor;
constructor = convType.GetConstructor(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic, null, ArgsToTypes(args), null);
if (constructor == null)
{
if (args.Length == 0)
throw new BadUsageException("Empty constructor for converter: " + convType.Name + " was not found. You must add a constructor without args (can be public or private)");
else
throw new BadUsageException("Constructor for converter: " + convType.Name + " with these arguments: (" + ArgsDesc(args) + ") was not found. You must add a constructor with this signature (can be public or private)");
}
try
{
Converter = (ConverterBase) constructor.Invoke(args);
}
catch (TargetInvocationException ex)
{
throw ex.InnerException;
}
}
#if ! MINI
else if (convType.IsEnum)
{
Converter = new EnumConverter(convType);
}
#endif
else
throw new BadUsageException("The custom converter must inherit from ConverterBase");
}
#endregion
#region " ArgsToTypes "
private Type[] ArgsToTypes(object[] args)
{
if (args == null)
throw new BadUsageException("The args to the constructor can be null, if you not want to pass the ConverterKind.");
Type[] res = new Type[args.Length];
for (int i = 0; i < args.Length; i++)
{
if (args[i] == null)
res[i] = typeof (object);
else
res[i] = args[i].GetType();
}
return res;
}
private string ArgsDesc(object[] args)
{
string res = DisplayType(args[0]);
for(int i = 1; i < args.Length; i++)
res += ", " + DisplayType(args[i]);
return res;
}
private string DisplayType(object o)
{
if (o == null)
return "Object";
else
return o.GetType().Name;
}
#endregion
internal void ValidateTypes(FieldInfo fi)
{
bool valid = false;
Type fieldType = fi.FieldType;
#if NET_2_0
if (fieldType.IsValueType &&
fieldType.IsGenericType &&
fieldType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
fieldType = fieldType.GetGenericArguments()[0];
}
#endif
switch (Kind)
{
case ConverterKind.None:
valid = true;
break;
case ConverterKind.Date:
valid = typeof(DateTime) == fieldType;
break;
case ConverterKind.Byte:
case ConverterKind.SByte:
case ConverterKind.Int16:
case ConverterKind.Int32:
case ConverterKind.Int64:
case ConverterKind.UInt16:
case ConverterKind.UInt32:
case ConverterKind.UInt64:
case ConverterKind.Decimal:
case ConverterKind.Double:
case ConverterKind.Single:
case ConverterKind.Boolean:
valid = Kind.ToString() == fieldType.UnderlyingSystemType.Name;
break;
}
if (valid == false)
throw new BadUsageException(
"The Converter of the field: '" + fi.Name + "' is wrong. The field is of Type: " + fieldType.Name + " and the converter is for type: " + Kind.ToString());
}
}
}

View file

@ -1,31 +0,0 @@
#region " © Copyright 2005-07 to Marcos Meli - http://www.marcosmeli.com.ar"
// Errors, suggestions, contributions, send a mail to: marcos@filehelpers.com.
#endregion
using System;
namespace FileHelpers
{
/// <summary>Indicates a diferent delimiter for this field. </summary>
/// <remarks>See the <a href="attributes.html">Complete Attributes List</a> for more clear info and examples of each one.</remarks>
/// <seealso href="attributes.html">Attributes List</seealso>
/// <seealso href="quick_start.html">Quick Start Guide</seealso>
/// <seealso href="examples.html">Examples of Use</seealso>
[AttributeUsage(AttributeTargets.Field)]
public sealed class FieldDelimiterAttribute : FieldAttribute
{
internal string mSeparator;
/// <summary>Indicates a diferent delimiter for this field. </summary>
/// <param name="separator">The separator string used to split the fields of the record.</param>
public FieldDelimiterAttribute(string separator)
{
if (separator == null || separator.Length == 0)
throw new BadUsageException("The separator parameter of the FieldDelimited attribute can't be null or empty");
else
this.mSeparator = separator;
}
}
}

View file

@ -1,32 +0,0 @@
#region " © Copyright 2005-07 to Marcos Meli - http://www.marcosmeli.com.ar"
// Errors, suggestions, contributions, send a mail to: marcos@filehelpers.com.
#endregion
using System;
namespace FileHelpers
{
/// <summary>Indicates the length of a FixedLength field.</summary>
/// <remarks>See the <a href="attributes.html">Complete Attributes List</a> for more clear info and examples of each one.</remarks>
/// <seealso href="attributes.html">Attributes List</seealso>
/// <seealso href="quick_start.html">Quick Start Guide</seealso>
/// <seealso href="examples.html">Examples of Use</seealso>
[AttributeUsage(AttributeTargets.Field)]
public sealed class FieldFixedLengthAttribute : FieldAttribute
{
internal int Length;
/// <summary>Indicates the length of a FixedLength field.</summary>
/// <param name="length">The length of the field.</param>
public FieldFixedLengthAttribute(int length)
{
if (length > 0)
this.Length = length;
else
throw new BadUsageException("The length parameter must be > 0");
}
}
}

View file

@ -1,23 +0,0 @@
#region " © Copyright 2005-07 to Marcos Meli - http://www.marcosmeli.com.ar"
// Errors, suggestions, contributions, send a mail to: marcos@filehelpers.com.
#endregion
using System;
namespace FileHelpers
{
/// <summary>Indicates that the target field is completely ignored by the Engine (i.e. This field don´t exists for the library).</summary>
/// <remarks>See the <a href="attributes.html">Complete Attributes List</a> for more clear info and examples of each one.</remarks>
/// <seealso href="attributes.html">Attributes List</seealso>
/// <seealso href="quick_start.html">Quick Start Guide</seealso>
/// <seealso href="examples.html">Examples of Use</seealso>
[AttributeUsage(AttributeTargets.Field)]
public sealed class FieldIgnoredAttribute : FieldAttribute
{
/// <summary>Indicates that the target field is ignored by the Engine AND NOT IS IN THE FILE.</summary>
public FieldIgnoredAttribute()
{}
}
}

View file

@ -1,23 +0,0 @@
#region " © Copyright 2005-07 to Marcos Meli - http://www.marcosmeli.com.ar"
// Errors, suggestions, contributions, send a mail to: marcos@filehelpers.com.
#endregion
using System;
namespace FileHelpers
{
/// <summary>Indicates the target field has a new line before his value (i.e. indicates that the records has multiple lines, and this field is in the begining of a line)</summary>
/// <remarks>See the <a href="attributes.html">Complete Attributes List</a> for more clear info and examples of each one.</remarks>
/// <seealso href="attributes.html">Attributes List</seealso>
/// <seealso href="quick_start.html">Quick Start Guide</seealso>
/// <seealso href="examples.html">Examples of Use</seealso>
[AttributeUsage(AttributeTargets.Field)]
public sealed class FieldInNewLineAttribute: Attribute
{
/// <summary>Indicates the target field has a new line before his value (i.e. indicates that the records has multiple lines, and this field is in the begining of a line)</summary>
public FieldInNewLineAttribute()
{}
}
}

View file

@ -1,50 +0,0 @@
#region " © Copyright 2005-07 to Marcos Meli - http://www.marcosmeli.com.ar"
// Errors, suggestions, contributions, send a mail to: marcos@filehelpers.com.
#endregion
using System;
namespace FileHelpers
{
/// <summary>Indicates the value to assign to the field in the case of find a "NULL".</summary>
/// <remarks>See the <a href="attributes.html">Complete Attributes List</a> for more clear info and examples of each one.</remarks>
/// <seealso href="attributes.html">Attributes List</seealso>
/// <seealso href="quick_start.html">Quick Start Guide</seealso>
/// <seealso href="examples.html">Examples of Use</seealso>
[AttributeUsage(AttributeTargets.Field)]
public sealed class FieldNullValueAttribute : Attribute
{
internal object NullValue;
// internal bool NullValueOnWrite = false;
/// <summary>Indicates directly the null value.</summary>
/// <param name="nullValue">The value to assign in the "NULL" case.</param>
public FieldNullValueAttribute(object nullValue)
{
NullValue = nullValue;
// NullValueOnWrite = useOnWrite;
}
// /// <summary>Indicates directly the null value.</summary>
// /// <param name="nullValue">The value to assign in the "NULL" case.</param>
// public FieldNullValueAttribute(object nullValue): this(nullValue, false)
// {}
// /// <summary>Indicates a type and a string to be converted to that type.</summary>
// /// <param name="type">The type of the null value.</param>
// /// <param name="nullValue">The string to be converted to the specified type.</param>
// /// <param name="useOnWrite">Indicates that if the field has that value when the library writes, then the engine use an empty string.</param>
// public FieldNullValueAttribute(Type type, string nullValue, bool useOnWrite):this(Convert.ChangeType(nullValue, type, null), useOnWrite)
// {}
/// <summary>Indicates a type and a string to be converted to that type.</summary>
/// <param name="type">The type of the null value.</param>
/// <param name="nullValue">The string to be converted to the specified type.</param>
public FieldNullValueAttribute(Type type, string nullValue):this(Convert.ChangeType(nullValue, type, null))
{}
}
}

View file

@ -1,28 +0,0 @@
#region " © Copyright 2005-07 to Marcos Meli - http://www.marcosmeli.com.ar"
// Errors, suggestions, contributions, send a mail to: marcos@filehelpers.com.
#endregion
using System;
namespace FileHelpers
{
/// <summary>Indicates that the target field is included only under some circunstances.</summary>
/// <remarks>See the <a href="attributes.html">Complete Attributes List</a> for more clear info and examples of each one.</remarks>
/// <seealso href="attributes.html">Attributes List</seealso>
/// <seealso href="quick_start.html">Quick Start Guide</seealso>
/// <seealso href="examples.html">Examples of Use</seealso>
[AttributeUsage(AttributeTargets.Field)]
public sealed class FieldOptionalAttribute : Attribute
{
#region " Constructors "
/// <summary>Indicates that the target field is included only under some circunstances.</summary>
public FieldOptionalAttribute()
{
}
#endregion
}
}

View file

@ -1,75 +0,0 @@
#region " © Copyright 2005-07 to Marcos Meli - http://www.marcosmeli.com.ar"
// Errors, suggestions, contributions, send a mail to: marcos@filehelpers.com.
#endregion
using System;
using System.ComponentModel;
namespace FileHelpers
{
/// <summary>Indicates that the field must be read and written like a Quoted String. (by default "")</summary>
/// <remarks>See the <a href="attributes.html">Complete Attributes List</a> for more clear info and examples of each one.</remarks>
/// <seealso href="attributes.html">Attributes List</seealso>
/// <seealso href="quick_start.html">Quick Start Guide</seealso>
/// <seealso href="examples.html">Examples of Use</seealso>
[AttributeUsage(AttributeTargets.Field)]
public sealed class FieldQuotedAttribute : Attribute
{
internal char QuoteChar;
internal QuoteMode QuoteMode = QuoteMode.AlwaysQuoted;
internal MultilineMode QuoteMultiline = MultilineMode.AllowForBoth;
/// <summary>Indicates that the field must be read and written like a Quoted String with double quotes.</summary>
public FieldQuotedAttribute() : this('\"')
{
}
/// <summary>Indicates that the field must be read and written like a Quoted String with the specified char.</summary>
/// <param name="quoteChar">The char used to quote the string.</param>
public FieldQuotedAttribute(char quoteChar):this(quoteChar, QuoteMode.OptionalForRead, MultilineMode.AllowForBoth)
{
}
/// <summary>Indicates that the field must be read and written like a "Quoted String" (that can be optional depending of the mode).</summary>
/// <param name="mode">Indicates if the handling of optionals in the quoted field.</param>
public FieldQuotedAttribute(QuoteMode mode) : this('\"', mode)
{}
/// <summary>Indicates that the field must be read and written like a Quoted String (that can be optional).</summary>
/// <param name="mode">Indicates if the handling of optionals in the quoted field.</param>
/// <param name="multiline">Indicates if the field can span multiple lines.</param>
public FieldQuotedAttribute(QuoteMode mode, MultilineMode multiline):this('"', mode, multiline)
{}
/// <summary>Indicates that the field must be read and written like a Quoted String (that can be optional).</summary>
/// <param name="quoteChar">The char used to quote the string.</param>
/// <param name="mode">Indicates if the handling of optionals in the quoted field.</param>
public FieldQuotedAttribute(char quoteChar, QuoteMode mode):this(quoteChar, mode, MultilineMode.AllowForBoth)
{}
/// <summary>Indicates that the field must be read and written like a Quoted String (that can be optional).</summary>
/// <param name="quoteChar">The char used to quote the string.</param>
/// <param name="mode">Indicates if the handling of optionals in the quoted field.</param>
/// <param name="multiline">Indicates if the field can span multiple lines.</param>
public FieldQuotedAttribute(char quoteChar, QuoteMode mode, MultilineMode multiline)
{
QuoteChar = quoteChar;
QuoteMode = mode;
QuoteMultiline = multiline;
}
/// <summary>Indicates that the field must be read and written like a Quoted String with double quotes.</summary>
/// <param name="multiline">Indicates if the field can span multiple lines.</param>
public FieldQuotedAttribute(MultilineMode multiline) : this('\"', QuoteMode.OptionalForRead, multiline)
{}
}
}

View file

@ -1,57 +0,0 @@
#region " © Copyright 2005-07 to Marcos Meli - http://www.marcosmeli.com.ar"
// Errors, suggestions, contributions, send a mail to: marcos@filehelpers.com.
#endregion
using System;
namespace FileHelpers
{
/// <summary>Indicates the <see cref="TrimMode"/> used after read to truncate the field. </summary>
/// <remarks>See the <a href="attributes.html">Complete Attributes List</a> for more clear info and examples of each one.</remarks>
/// <seealso href="attributes.html">Attributes List</seealso>
/// <seealso href="quick_start.html">Quick Start Guide</seealso>
/// <seealso href="examples.html">Examples of Use</seealso>
[AttributeUsage(AttributeTargets.Field)]
public sealed class FieldTrimAttribute : Attribute
{
internal Char[] TrimChars;
internal TrimMode TrimMode;
private static char[] WhitespaceChars = new char[]
{
'\t', '\n', '\v', '\f', '\r', ' ', '\x00a0', '\u2000', '\u2001', '\u2002', '\u2003', '\u2004', '\u2005', '\u2006', '\u2007', '\u2008',
'\u2009', '\u200a', '\u200b', '\u3000', '\ufeff'
};
#region " Constructors "
/// <summary>Indicates the <see cref="TrimMode"/> used after read to truncate the field. By default trims the blank spaces and tabs.</summary>
/// <param name="mode">The <see cref="TrimMode"/> used after read.</param>
public FieldTrimAttribute(TrimMode mode)
: this(mode, WhitespaceChars)
{
}
/// <summary>Indicates the <see cref="TrimMode"/> used after read to truncate the field. </summary>
/// <param name="mode">The <see cref="TrimMode"/> used after read.</param>
/// <param name="chars">A list of chars used to trim.</param>
public FieldTrimAttribute(TrimMode mode, params char[] chars)
{
TrimMode = mode;
Array.Sort(chars);
TrimChars = chars;
}
/// <summary>Indicates the <see cref="TrimMode"/> used after read to truncate the field. </summary>
/// <param name="mode">The <see cref="TrimMode"/> used after read.</param>
/// <param name="trimChars">A string of chars used to trim.</param>
public FieldTrimAttribute(TrimMode mode, string trimChars)
:this(mode, trimChars.ToCharArray())
{
}
#endregion
}
}

View file

@ -1,33 +0,0 @@
#region " © Copyright 2005-07 to Marcos Meli - http://www.marcosmeli.com.ar"
// Errors, suggestions, contributions, send a mail to: marcos@filehelpers.com.
#endregion
using System;
namespace FileHelpers
{
/// <summary>Indicates that this class represents a fixed length record.</summary>
/// <remarks>See the <a href="attributes.html">Complete Attributes List</a> for more clear info and examples of each one.</remarks>
/// <seealso href="attributes.html">Attributes List</seealso>
/// <seealso href="quick_start.html">Quick Start Guide</seealso>
/// <seealso href="examples.html">Examples of Use</seealso>
[AttributeUsage(AttributeTargets.Class)]
public sealed class FixedLengthRecordAttribute : TypedRecordAttribute
{
internal FixedMode mFixedMode = FixedMode.ExactLength;
/// <summary>Indicates that this class represents a fixed length record. By default requieres that the records has the length equals to the sum of each field length.</summary>
public FixedLengthRecordAttribute()
{}
/// <summary>Indicates that this class represents a fixed length record with the specified variable record behavior.</summary>
/// <param name="mode">The <see cref="FixedMode"/> used for variable length records.</param>
public FixedLengthRecordAttribute(FixedMode mode)
{
mFixedMode = mode;
}
}
}

View file

@ -1,41 +0,0 @@
#region " © Copyright 2005-07 to Marcos Meli - http://www.marcosmeli.com.ar"
// Errors, suggestions, contributions, send a mail to: marcos@filehelpers.com.
#endregion
using System;
namespace FileHelpers
{
/// <summary>Indicates that the engine must ignore commented lines while reading.</summary>
/// <remarks>See the <a href="attributes.html">Complete Attributes List</a> for more clear info and examples of each one.</remarks>
/// <seealso href="attributes.html">Attributes List</seealso>
/// <seealso href="quick_start.html">Quick Start Guide</seealso>
/// <seealso href="examples.html">Examples of Use</seealso>
[AttributeUsage(AttributeTargets.Class)]
public sealed class IgnoreCommentedLinesAttribute : Attribute
{
internal string mCommentMarker;
internal bool mAnyPlace = true;
/// <summary>Indicates that the engine must ignore commented lines while reading. (The Comment Marker can appear in any place with spaces or tabs at his left)</summary>
/// <param name="commentMarker">The comment marker used to ignore the lines</param>
public IgnoreCommentedLinesAttribute(string commentMarker): this(commentMarker, true)
{
}
/// <summary>Indicates that the engine must ignore commented lines while reading.</summary>
/// <param name="commentMarker">The comment marker used to ignore the lines</param>
/// <param name="anyPlace">Indicates if the comment can have spaces or tabs at left (true by default)</param>
public IgnoreCommentedLinesAttribute(string commentMarker, bool anyPlace)
{
if (commentMarker == null || commentMarker.Trim().Length == 0)
throw new BadUsageException("The comment string parameter cant be null or empty.");
mCommentMarker = commentMarker.Trim();
mAnyPlace = anyPlace;
}
}
}

View file

@ -1,31 +0,0 @@
#region " © Copyright 2005-07 to Marcos Meli - http://www.marcosmeli.com.ar"
// Errors, suggestions, contributions, send a mail to: marcos@filehelpers.com.
#endregion
using System;
namespace FileHelpers
{
/// <summary>Indicates that the engine must ignore the empty lines while reading.</summary>
/// <remarks>See the <a href="attributes.html">Complete Attributes List</a> for more clear info and examples of each one.</remarks>
/// <seealso href="attributes.html">Attributes List</seealso>
/// <seealso href="quick_start.html">Quick Start Guide</seealso>
/// <seealso href="examples.html">Examples of Use</seealso>
[AttributeUsage(AttributeTargets.Class)]
public sealed class IgnoreEmptyLinesAttribute : Attribute
{
internal bool mIgnoreSpaces = false;
/// <summary>Indicates that the engine must ignore the empty lines while reading.</summary>
public IgnoreEmptyLinesAttribute()
{}
/// <summary>Indicates that the engine must ignore the empty lines while reading.</summary>
/// <param name="ignoreSpaces">Indicates if also must ignore lines with spaces.</param>
public IgnoreEmptyLinesAttribute(bool ignoreSpaces)
{
mIgnoreSpaces = ignoreSpaces;
}
}
}

View file

@ -1,34 +0,0 @@
#region " © Copyright 2005-07 to Marcos Meli - http://www.marcosmeli.com.ar"
// Errors, suggestions, contributions, send a mail to: marcos@filehelpers.com.
#endregion
using System;
namespace FileHelpers
{
/// <summary>Indicates the number of first lines to be discarded.</summary>
/// <remarks>See the <a href="attributes.html">Complete Attributes List</a> for more clear info and examples of each one.</remarks>
/// <seealso href="attributes.html">Attributes List</seealso>
/// <seealso href="quick_start.html">Quick Start Guide</seealso>
/// <seealso href="examples.html">Examples of Use</seealso>
[AttributeUsage(AttributeTargets.Class)]
public sealed class IgnoreFirstAttribute : Attribute
{
internal int NumberOfLines;
/// <summary>Indicates that the first line must be discarded.</summary>
public IgnoreFirstAttribute() : this(1)
{
}
/// <summary>Indicates the number of first lines to be ignored.</summary>
/// <param name="numberOfLines">The number of first lines to be discarded.</param>
public IgnoreFirstAttribute(int numberOfLines)
{
NumberOfLines = numberOfLines;
}
}
}

View file

@ -1,33 +0,0 @@
#region " © Copyright 2005-07 to Marcos Meli - http://www.marcosmeli.com.ar"
// Errors, suggestions, contributions, send a mail to: marcos@filehelpers.com.
#endregion
using System;
namespace FileHelpers
{
/// <summary>Indicates the number of lines to be discarded at the end.</summary>
/// <remarks>See the <a href="attributes.html">Complete Attributes List</a> for more clear info and examples of each one.</remarks>
/// <seealso href="attributes.html">Attributes List</seealso>
/// <seealso href="quick_start.html">Quick Start Guide</seealso>
/// <seealso href="examples.html">Examples of Use</seealso>
[AttributeUsage(AttributeTargets.Class)]
public sealed class IgnoreLastAttribute : Attribute
{
internal int NumberOfLines;
/// <summary>Indicates that the last line must be discarded.</summary>
public IgnoreLastAttribute() : this(1)
{
}
/// <summary>Indicates the number of last lines to be ignored at the end.</summary>
/// <param name="numberOfLines">The number of lines to be discarded at end.</param>
public IgnoreLastAttribute(int numberOfLines)
{
NumberOfLines = numberOfLines;
}
}
}

View file

@ -1,30 +0,0 @@
#region " © Copyright 2005-07 to Marcos Meli - http://www.marcosmeli.com.ar"
// Errors, suggestions, contributions, send a mail to: marcos@filehelpers.com.
#endregion
using System;
using System.ComponentModel;
namespace FileHelpers
{
/// <summary>Base class for the record types..</summary>
/// <remarks>See the <a href="attributes.html">Complete Attributes List</a> for more clear info and examples of each one.</remarks>
/// <seealso href="attributes.html">Attributes List</seealso>
/// <seealso href="quick_start.html">Quick Start Guide</seealso>
/// <seealso href="examples.html">Examples of Use</seealso>
[EditorBrowsable(EditorBrowsableState.Never)]
public abstract class TypedRecordAttribute : Attribute
{
#region " Constructors "
/// <summary>Abstract class, see inheritors.</summary>
protected TypedRecordAttribute()
{
}
#endregion
}
}

View file

@ -1,485 +0,0 @@
#region " © Copyright 2005-07 to Marcos Meli - http://www.marcosmeli.com.ar"
// Errors, suggestions, contributions, send a mail to: marcos@filehelpers.com.
#endregion
using System;
using System.Globalization;
namespace FileHelpers
{
/// <summary>Class that provides static methods that returns a default <see cref="ConverterBase">Converter</see> to the basic types.</summary>
/// <remarks>Used by the <see cref="FileHelpers.FieldConverterAttribute"/>.</remarks>
internal sealed class ConvertHelpers
{
private const string DefaultDecimalSep = ".";
#region " Constructors "
// Not allow direct creation
private ConvertHelpers()
{
}
#endregion
#region " CreateCulture "
static CultureInfo CreateCulture(string decimalSep)
{
CultureInfo ci = new CultureInfo(CultureInfo.CurrentCulture.LCID);
if (decimalSep == ".")
{
ci.NumberFormat.NumberDecimalSeparator = ".";
ci.NumberFormat.NumberGroupSeparator = ",";
}
else if (decimalSep == ",")
{
ci.NumberFormat.NumberDecimalSeparator = ",";
ci.NumberFormat.NumberGroupSeparator = ".";
}
else
throw new BadUsageException("You can only use '.' or ',' as decimal or grup separators");
return ci;
}
#endregion
#region " GetDefaultConverter "
internal static ConverterBase GetDefaultConverter(string fieldName, Type fieldType)
{
#if NET_2_0
if (fieldType.IsValueType &&
fieldType.IsGenericType &&
fieldType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
fieldType = fieldType.GetGenericArguments()[0];
}
#endif
// Try to assign a default Converter
if (fieldType == typeof(string))
return null;
else if (fieldType == typeof(Int16))
return new Int16Converter();
else if (fieldType == typeof(Int32))
return new Int32Converter();
else if (fieldType == typeof(Int64))
return new Int64Converter();
else if (fieldType == typeof(SByte))
return new SByteConverter();
else if (fieldType == typeof(UInt16))
return new UInt16Converter();
else if (fieldType == typeof(UInt32))
return new UInt32Converter();
else if (fieldType == typeof(UInt64))
return new UInt64Converter();
else if (fieldType == typeof(Byte))
return new ByteConverter();
else if (fieldType == typeof(Decimal))
return new DecimalConverter();
else if (fieldType == typeof(Double))
return new DoubleConverter();
else if (fieldType == typeof(Single))
return new SingleConverter();
else if (fieldType == typeof(DateTime))
return new DateTimeConverter();
else if (fieldType == typeof(Boolean))
return new BooleanConverter();
#if ! MINI
else if (fieldType.IsEnum)
return new EnumConverter(fieldType);
#endif
throw new BadUsageException("The field: '" + fieldName + "' of type: " + fieldType.Name + " is a non system type, so this field need a CustomConverter (see the docs for more info).");
}
#endregion
internal abstract class CultureConverter
: ConverterBase
{
protected CultureInfo mCulture;
protected Type mType;
public CultureConverter(Type T, string decimalSep)
{
mCulture = CreateCulture(decimalSep);
mType = T;
}
public sealed override string FieldToString(object from)
{
return ((IConvertible)from).ToString(mCulture);
}
public sealed override object StringToField(string from)
{
object val;
try
{
val = ParseString(from);
}
catch
{
throw new ConvertException(from, mType);
}
return val;
}
protected abstract object ParseString(string from);
}
internal sealed class ByteConverter : CultureConverter
{
public ByteConverter()
: this(DefaultDecimalSep)
{}
public ByteConverter(string decimalSep)
: base(typeof(Byte), decimalSep)
{}
protected override object ParseString(string from)
{
return Byte.Parse(StringHelper.RemoveBlanks(from), NumberStyles.Number, mCulture);
}
}
internal sealed class UInt16Converter : CultureConverter
{
public UInt16Converter()
: this(DefaultDecimalSep)
{}
public UInt16Converter(string decimalSep)
: base(typeof(UInt16), decimalSep)
{ }
protected override object ParseString(string from)
{
return UInt16.Parse(StringHelper.RemoveBlanks(from), NumberStyles.Number, mCulture);
}
}
internal sealed class UInt32Converter : CultureConverter
{
public UInt32Converter()
: this(DefaultDecimalSep)
{}
public UInt32Converter(string decimalSep)
: base(typeof(UInt32), decimalSep)
{ }
protected override object ParseString(string from)
{
return UInt32.Parse(StringHelper.RemoveBlanks(from), NumberStyles.Number, mCulture);
}
}
internal sealed class UInt64Converter : CultureConverter
{
public UInt64Converter()
: this(DefaultDecimalSep)
{}
public UInt64Converter(string decimalSep)
: base(typeof(UInt64), decimalSep)
{ }
protected override object ParseString(string from)
{
return UInt64.Parse(StringHelper.RemoveBlanks(from), NumberStyles.Number, mCulture);
}
}
#region " Int16, Int32, Int64 Converters "
#region " Convert Classes "
internal sealed class SByteConverter : CultureConverter
{
public SByteConverter()
: this(DefaultDecimalSep)
{}
public SByteConverter(string decimalSep)
: base(typeof(SByte), decimalSep)
{ }
protected override object ParseString(string from)
{
return SByte.Parse(StringHelper.RemoveBlanks(from), NumberStyles.Number, mCulture);
}
}
internal sealed class Int16Converter : CultureConverter
{
public Int16Converter()
: this(DefaultDecimalSep)
{}
public Int16Converter(string decimalSep)
: base(typeof(Int16), decimalSep)
{ }
protected override object ParseString(string from)
{
return Int16.Parse(StringHelper.RemoveBlanks(from), NumberStyles.Number, mCulture);
}
}
internal sealed class Int32Converter : CultureConverter
{
public Int32Converter()
: this(DefaultDecimalSep)
{}
public Int32Converter(string decimalSep)
: base(typeof(Int32), decimalSep)
{ }
protected override object ParseString(string from)
{
return Int32.Parse(StringHelper.RemoveBlanks(from), NumberStyles.Number, mCulture);
}
}
internal sealed class Int64Converter : CultureConverter
{
public Int64Converter()
: this(DefaultDecimalSep)
{}
public Int64Converter(string decimalSep)
: base(typeof(Int64), decimalSep)
{ }
protected override object ParseString(string from)
{
return Int64.Parse(StringHelper.RemoveBlanks(from), NumberStyles.Number, mCulture);
}
}
#endregion
#endregion
#region " Single, Double, DecimalConverters "
#region " Convert Classes "
internal sealed class DecimalConverter : CultureConverter
{
public DecimalConverter()
: this(DefaultDecimalSep)
{}
public DecimalConverter(string decimalSep)
:base (typeof(Decimal), decimalSep)
{
}
protected override object ParseString(string from)
{
return Decimal.Parse(StringHelper.RemoveBlanks(from), NumberStyles.Number, mCulture);
}
}
internal sealed class SingleConverter : CultureConverter
{
public SingleConverter()
: this(DefaultDecimalSep)
{}
public SingleConverter(string decimalSep)
: base(typeof(Single), decimalSep)
{}
protected override object ParseString(string from)
{
return Single.Parse(StringHelper.RemoveBlanks(from), NumberStyles.Number, mCulture);
}
}
internal sealed class DoubleConverter : CultureConverter
{
public DoubleConverter()
: this(DefaultDecimalSep)
{}
public DoubleConverter(string decimalSep)
:base(typeof(Double), decimalSep)
{
}
protected override object ParseString(string from)
{
return Double.Parse(StringHelper.RemoveBlanks(from), NumberStyles.Number, mCulture);
}
}
#endregion
#endregion
#region " Date Converters "
#region " Convert Classes "
internal sealed class DateTimeConverter : ConverterBase
{
string mFormat;
public DateTimeConverter() : this(ConverterBase.DefaultDateTimeFormat)
{
}
public DateTimeConverter(string format)
{
if (format == null || format == String.Empty)
throw new BadUsageException("The format of the DateTime Converter can be null or empty.");
try
{
string tmp = DateTime.Now.ToString(format);
}
catch
{
throw new BadUsageException("The format: '" + format + " is invalid for the DateTime Converter.");
}
mFormat = format;
}
//static CultureInfo mInvariant = System.Globalization.CultureInfo.InvariantCulture;
public override object StringToField(string from)
{
if (from == null) from = string.Empty;
object val;
try
{
val = DateTime.ParseExact(from.Trim(), mFormat, null);
}
catch
{
string extra = String.Empty;
if (from.Length > mFormat.Length)
extra = " There are more chars than in the format string: '" + mFormat + "'";
else if (from.Length < mFormat.Length)
extra = " There are less chars than in the format string: '" + mFormat + "'";
else
extra = " Using the format: '" + mFormat + "'";
throw new ConvertException(from, typeof (DateTime), extra);
}
return val;
}
public override string FieldToString(object from)
{
return Convert.ToDateTime(from).ToString(mFormat);
}
}
#endregion
#endregion
#region " Boolean Converters "
#region " Convert Classes "
internal sealed class BooleanConverter : ConverterBase
{
private string mTrueString = null;
private string mFalseString = null;
private string mTrueStringLower = null;
private string mFalseStringLower = null;
public BooleanConverter()
{
}
public BooleanConverter(string trueStr, string falseStr)
{
mTrueString = trueStr;
mFalseString = falseStr;
mTrueStringLower = trueStr.ToLower();
mFalseStringLower = falseStr.ToLower();
}
public override object StringToField(string from)
{
object val;
try
{
string testTo = from.ToLower();
if (mTrueString == null)
{
testTo = testTo.Trim();
if (testTo == "true" || testTo == "1")
val = true;
else if (testTo == "false" || testTo == "0" || testTo == "")
val = false;
else
throw new Exception();
}
else
{
if (testTo == mTrueStringLower || testTo.Trim() == mTrueStringLower)
val = true;
else if (testTo == mFalseStringLower || testTo.Trim() == mFalseStringLower)
val = false;
else
throw new ConvertException(from, typeof(bool), "The string: " + from + " cant be recognized as boolean using the true/false values: " + mTrueString + "/" + mFalseString);
}
}
catch
{
throw new ConvertException(from, typeof (Boolean));
}
return val;
}
public override string FieldToString(object from)
{
bool b = Convert.ToBoolean(from);
if (b)
if (mTrueString == null)
return "True";
else
return mTrueString;
else
if (mFalseString == null)
return "False";
else
return mFalseString;
}
}
#endregion
#endregion
}
}

View file

@ -1,97 +0,0 @@
using System;
#region " © Copyright 2005-07 to Marcos Meli - http://www.marcosmeli.com.ar"
// Errors, suggestions, contributions, send a mail to: marcos@filehelpers.com.
#endregion
namespace FileHelpers
{
/// <summary>
/// Base class to provide bidirectional
/// Field - String convertion.
/// </summary>
public abstract class ConverterBase
{
private static string mDefaultDateTimeFormat = "ddMMyyyy";
/// <summary>
/// <para>Allow you to set the default Date Format used for the converter.</para>
/// <para>With the same format that the .NET framework.</para>
/// <para>By default: "ddMMyyyy"</para>
/// </summary>
public static string DefaultDateTimeFormat
{
get { return mDefaultDateTimeFormat; }
set
{
try
{
string tmp = DateTime.Now.ToString(value);
}
catch
{
throw new BadUsageException("The format: '" + value + " is invalid for the DateTime Converter.");
}
mDefaultDateTimeFormat= value;
}
}
/// <summary>
/// Convert a string in the file to a field value.
/// </summary>
/// <param name="from">The string to convert.</param>
/// <returns>The field value.</returns>
public abstract object StringToField(string from);
/// <summary>
/// Convert a field value to an string to write this to the file.
/// </summary>
/// <remarks>The basic implementation performs a: from.ToString();</remarks>
/// <param name="from">The field values to convert.</param>
/// <returns>The string representing the field value.</returns>
public virtual string FieldToString(object from)
{
if (from == null)
return string.Empty;
else
return from.ToString();
}
/// <summary>If the class retures false the engines don´t pass null values to the converter. If true the engines pass all the values to the converter.</summary>
protected internal virtual bool CustomNullHandling
{
get { return false; }
}
internal Type mDestinationType;
/// <summary>
/// Thorws a ConvertException with the passed values
/// </summary>
/// <param name="from">The source string.</param>
/// <param name="errorMsg">The custom error msg.</param>
protected void ThrowConvertException(string from, string errorMsg)
{
throw new ConvertException(from, mDestinationType, errorMsg);
}
// internal object mDefaultValue;
// /// <summary>
// /// Indicates
// /// </summary>
// protected object DefaultValueFromField
// {
// get
// {
// return mDefaultValue;
// }
// }
}
}

View file

@ -1,30 +0,0 @@
using System;
namespace FileHelpers
{
internal class EnumConverter : ConverterBase
{
Type mEnumType;
public EnumConverter(Type sourceEnum)
{
if (sourceEnum.IsEnum == false)
throw new BadUsageException("The sourceType must be an Enum and is of type " + sourceEnum.Name);
mEnumType = sourceEnum;
}
public override object StringToField(string from)
{
try
{
return Enum.Parse(mEnumType, from.Trim(), true);
}
catch (ArgumentException)
{
throw new ConvertException(from, mEnumType, "The value don't is on the Enum.");
}
}
}
}

View file

@ -1,136 +0,0 @@
using System;
namespace FileHelpers
{
internal sealed class ExtractedInfo
{
//public int CharsRemoved;
//public string ExtractedString;
internal string mCustomExtractedString = null;
public string ExtractedString()
{
if (mCustomExtractedString == null)
return new string(mLine.mLine, ExtractedFrom, ExtractedTo - ExtractedFrom + 1);
else
return mCustomExtractedString;
// return new string(mLine, .mLine.Substring(ExtractedFrom, ExtractedTo - ExtractedFrom + 1);
}
public int Length
{
get { return ExtractedTo - ExtractedFrom + 1;}
}
public LineInfo mLine;
public int ExtractedFrom;
public int ExtractedTo;
//public int ExtraLines;
//public string NewRestOfLine;
//public string TrailString;
public ExtractedInfo(LineInfo line)
{
mLine = line;
ExtractedFrom = line.mCurrentPos;
ExtractedTo = line.mLine.Length - 1;
//CharsRemoved = ExtractedTo - ExtractedFrom + 1;
//ExtraLines = 0;
// NewRestOfLine = null;
}
public ExtractedInfo(LineInfo line, int extractTo)
{
mLine = line;
ExtractedFrom = line.mCurrentPos;
ExtractedTo = extractTo - 1;
//CharsRemoved = ExtractedTo - ExtractedFrom + 1;
//ExtraLines = 0;
// NewRestOfLine = null;
}
public ExtractedInfo(string customExtract)
{
mCustomExtractedString = customExtract;
}
public void TrimStart(char[] sortedToTrim)
{
if (mCustomExtractedString != null)
mCustomExtractedString = mCustomExtractedString.TrimStart(sortedToTrim);
else
while(ExtractedFrom < ExtractedTo&& Array.BinarySearch(sortedToTrim, mLine.mLine[ExtractedFrom]) >= 0)
ExtractedFrom++;
}
public void TrimEnd(char[] sortedToTrim)
{
if (mCustomExtractedString != null)
mCustomExtractedString = mCustomExtractedString.TrimEnd(sortedToTrim);
else
while(ExtractedTo > ExtractedFrom && Array.BinarySearch(sortedToTrim, mLine.mLine[ExtractedTo]) >= 0)
ExtractedTo--;
}
public void TrimBoth(char[] sortedToTrim)
{
if (mCustomExtractedString != null)
mCustomExtractedString = mCustomExtractedString.Trim(sortedToTrim);
else
{
while(ExtractedFrom <= ExtractedTo && Array.BinarySearch(sortedToTrim, mLine.mLine[ExtractedFrom]) >= 0)
{
ExtractedFrom++;
}
while(ExtractedTo > ExtractedFrom && Array.BinarySearch(sortedToTrim, mLine.mLine[ExtractedTo]) >= 0)
{
ExtractedTo--;
}
}
}
//
// public ExtractedInfo(string extracted, int charsRem, int lines)
// {
// ExtractedString = extracted;
// CharsRemoved = charsRem;
// ExtraLines = lines;
// NewRestOfLine = null;
// }
internal static readonly ExtractedInfo Empty = new ExtractedInfo(string.Empty);
public bool HasOnlyThisChars(char[] sortedArray)
{
// Check if the chars at pos or right are empty ones
if (mCustomExtractedString != null)
{
int pos = 0;
while ( pos < mCustomExtractedString.Length &&
Array.BinarySearch(sortedArray, mCustomExtractedString[pos]) >= 0 )
{
pos++;
}
return pos == mCustomExtractedString.Length;
}
else
{
int pos = ExtractedFrom;
while(pos <= ExtractedTo && Array.BinarySearch(sortedArray, mLine.mLine[pos]) >= 0)
{
pos++;
}
return pos > ExtractedTo;
}
}
}
}

View file

@ -1,165 +0,0 @@
using System;
using System.Globalization;
using System.IO;
using System.Text;
namespace FileHelpers
{
internal sealed class ForwardReader
{
TextReader mReader;
private string[] mFowardStrings;
private int mForwardIndex = 0;
internal char[] mEOF = StringHelper.NewLine.ToCharArray();
internal int mCapacityHint = 64;
private int mRemaingLines = 0;
public int RemainingLines
{
get { return mRemaingLines; }
}
private int mLineNumber = 0;
public int LineNumber
{
get {return mLineNumber - 1;}
}
//
// int mPos = 0;
// int MaxRecordSize = 1024 * 8;
// char[] mBuffer;
//
internal ForwardReader(TextReader reader)
: this(reader, 0, 0)
{
}
internal ForwardReader(TextReader reader, int forwardLines):
this(reader, forwardLines, 0)
{
}
internal ForwardReader(TextReader reader, int forwardLines, int startLine)
{
mReader = reader;
mFowardLines = forwardLines;
mLineNumber = startLine;
mFowardStrings = new string[mFowardLines + 1];
mRemaingLines = mFowardLines + 1;
for (int i = 0; i < mFowardLines + 1; i++)
{
mFowardStrings[i] = mReader.ReadLine();
mLineNumber++;
if (mFowardStrings[i] == null)
{
mRemaingLines = i;
break;
}
}
}
// public string ReadToDelimiter(string del)
// {
// //StringBuilder builder = new StringBuilder(mCapacityHint);
//
// int right = mPos;
// while (true)
// {
// mReader.
//
// //mReader.Read()
//
// }
//
//
//
// if (builder.Length > 0)
// {
// return builder.ToString();
// }
// return null;
// }
private bool mDiscardForward = false;
public bool DiscardForward
{
get { return mDiscardForward; }
set { mDiscardForward = value; }
}
private int mFowardLines = 0;
public int FowardLines
{
get { return mFowardLines; }
}
public string ReadNextLine()
{
if (mRemaingLines <= 0)
return null;
else
{
string res = mFowardStrings[mForwardIndex];
if (mRemaingLines == (mFowardLines + 1))
{
mFowardStrings[mForwardIndex] = mReader.ReadLine();
mLineNumber++;
if (mFowardStrings[mForwardIndex] == null)
{
mRemaingLines--;
}
}
else
{
mRemaingLines--;
if (mDiscardForward)
return null;
}
mForwardIndex = (mForwardIndex + 1)%(mFowardLines + 1);
return res;
}
}
public string RemainingText
{
get
{
StringBuilder sb = new StringBuilder(100);
for (int i = 0; i < mRemaingLines + 1; i++)
{
sb.Append(mFowardStrings[(mForwardIndex + i)%(mFowardLines + 1)] + StringHelper.NewLine);
}
return sb.ToString();
}
}
public void Close()
{
mReader.Close();
}
}
}

View file

@ -1,166 +0,0 @@
#region " © Copyright 2005-07 to Marcos Meli - http://www.marcosmeli.com.ar"
// Errors, suggestions, contributions, send a mail to: marcos@filehelpers.com.
#endregion
using System;
using System.Globalization;
namespace FileHelpers
{
internal sealed class LineInfo
{
#region " Constructor "
static char[] mEmptyChars = new char[] {};
public LineInfo(string line)
{
mLineStr = line;
mLine = line == null ? mEmptyChars : line.ToCharArray();
mCurrentPos = 0;
}
#endregion
#region " Internal Fields "
//internal string mLine;
internal char[] mLine;
internal string mLineStr;
internal ForwardReader mReader;
internal int mCurrentPos;
private static char[] WhitespaceChars = new char[]
{
'\t', '\n', '\v', '\f', '\r', ' ', '\x00a0', '\u2000', '\u2001', '\u2002', '\u2003', '\u2004', '\u2005', '\u2006', '\u2007', '\u2008',
'\u2009', '\u200a', '\u200b', '\u3000', '\ufeff'
};
#endregion
public string CurrentString
{
get
{
return new string(mLine, mCurrentPos, mLine.Length - mCurrentPos);
}
}
public bool IsEOL()
{
return mCurrentPos >= mLine.Length;
}
public int CurrentLength
{
get
{
return mLine.Length - mCurrentPos;
}
}
public bool EmptyFromPos()
{
// Chek if the chars at pos or right are empty ones
int length = mLine.Length;
int pos = mCurrentPos;
while(pos < length && Array.BinarySearch(WhitespaceChars, mLine[pos]) >= 0)
{
pos++;
}
return pos >= length;
}
public void TrimStart()
{
TrimStartSorted(WhitespaceChars);
}
public void TrimStart(char[] toTrim)
{
Array.Sort(toTrim);
TrimStartSorted(toTrim);
}
private void TrimStartSorted(char[] toTrim)
{
// Move the pointer to the first non to Trim char
int length = mLine.Length;
while(mCurrentPos < length && Array.BinarySearch(toTrim, mLine[mCurrentPos]) >= 0)
{
mCurrentPos++;
}
}
public bool StartsWith(string str)
{
// Returns true if the string begin with str
if (mCurrentPos >= mLineStr.Length)
return false;
else
return mCompare.Compare(mLineStr, mCurrentPos, str.Length, str, 0, str.Length, CompareOptions.IgnoreCase) == 0;
}
public bool StartsWithTrim(string str)
{
int length = mLine.Length;
int pos = mCurrentPos;
while(pos < length && Array.BinarySearch(WhitespaceChars, mLine[pos]) >= 0)
{
pos++;
}
return mCompare.Compare(mLineStr, pos, str, 0, CompareOptions.IgnoreCase) == 0;
}
public void ReadNextLine()
{
mLineStr = mReader.ReadNextLine();
mLine = mLineStr.ToCharArray();
mCurrentPos = 0;
}
private static CompareInfo mCompare = CultureInfo.InvariantCulture.CompareInfo;
public int IndexOf(string foundThis)
{
// Bad performance with custom IndexOf
// if (foundThis.Length == 1)
// {
// char delimiter = foundThis[0];
// int pos = mCurrentPos;
// int length = mLine.Length;
//
// while (pos < length)
// {
// if (mLine[pos] == delimiter)
// return pos;
//
// pos++;
// }
// return -1;
// }
// else
// if (mLineStr == null)
// return -1;
// else
return mCompare.IndexOf(mLineStr, foundThis, mCurrentPos, CompareOptions.IgnoreCase);
}
internal void ReLoad(string line)
{
mLine = line == null ? mEmptyChars : line.ToCharArray();
mLineStr = line;
mCurrentPos = 0;
}
}
}

View file

@ -1,693 +0,0 @@
#region " © Copyright 2005-07 to Marcos Meli - http://www.marcosmeli.com.ar"
// Errors, suggestions, contributions, send a mail to: marcos@filehelpers.com.
#endregion
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Reflection;
using System.Security.Permissions;
using System.Security.Policy;
using System.Text;
#if ! MINI
//using System.Data;
using System.Text.RegularExpressions;
using System.Threading;
using System.Reflection.Emit;
#endif
namespace FileHelpers
{
/// <summary>An internal class used to store information about the Record Type.</summary>
/// <remarks>Is public to provide extensibility of DataSorage from outside the library.</remarks>
internal sealed class RecordInfo
{
#region " Internal Fields "
internal Type mRecordType;
internal FieldBase[] mFields;
internal int mIgnoreFirst = 0;
internal int mIgnoreLast = 0;
internal bool mIgnoreEmptyLines = false;
internal bool mIgnoreEmptySpaces = false;
internal string mCommentMarker = null;
internal bool mCommentAnyPlace = true;
internal RecordCondition mRecordCondition = RecordCondition.None;
internal string mRecordConditionSelector = string.Empty;
#if ! MINI
internal bool mNotifyRead;
internal bool mNotifyWrite;
private Regex mConditionRegEx = null;
#endif
internal int mFieldCount;
private ConstructorInfo mRecordConstructor;
private static readonly object[] mEmptyObjectArr = new object[] {};
private static readonly Type[] mEmptyTypeArr = new Type[] {};
#endregion
#region " Constructor "
/// <summary>The unique constructor for this class. It needs the subyacent record class.</summary>
/// <param name="recordType">The Type of the record class.</param>
internal RecordInfo(Type recordType)
{
mRecordType = recordType;
InitFields();
}
internal bool IsDelimited
{
get { return mFields[0] is DelimitedField; }
}
#endregion
#region " CreateAssingMethods "
//#if NET_2_0
private delegate object[] GetAllValuesCallback(object record);
private GetAllValuesCallback mGetAllValuesHandler;
private void CreateGetAllMethod()
{
if (mGetAllValuesHandler != null)
return;
DynamicMethod dm = new DynamicMethod("_GetAllValues_FH_RT_", MethodAttributes.Static | MethodAttributes.Public, CallingConventions.Standard, typeof(object[]), new Type[] { typeof(object) }, mRecordType, true);
ILGenerator generator = dm.GetILGenerator();
generator.DeclareLocal(typeof(object[]));
generator.DeclareLocal(mRecordType);
generator.Emit(OpCodes.Ldc_I4, mFieldCount);
generator.Emit(OpCodes.Newarr, typeof(object));
generator.Emit(OpCodes.Stloc_0);
generator.Emit(OpCodes.Ldarg_0);
generator.Emit(OpCodes.Castclass, mRecordType);
generator.Emit(OpCodes.Stloc_1);
for (int i = 0; i < mFieldCount; i++)
{
FieldBase field = mFields[i];
generator.Emit(OpCodes.Ldloc_0);
generator.Emit(OpCodes.Ldc_I4, i);
generator.Emit(OpCodes.Ldloc_1);
generator.Emit(OpCodes.Ldfld, field.mFieldInfo);
if (field.mFieldType.IsValueType)
{
generator.Emit(OpCodes.Box, field.mFieldType);
}
generator.Emit(OpCodes.Stelem_Ref);
//generator.EmitCall();
}
// return the value
generator.Emit(OpCodes.Ldloc_0);
generator.Emit(OpCodes.Ret);
mGetAllValuesHandler = (GetAllValuesCallback)dm.CreateDelegate(typeof(GetAllValuesCallback));
}
private delegate object CreateAndAssignCallback(object[] values);
private CreateAndAssignCallback mCreateHandler;
private void CreateAssingMethods()
{
if (mCreateHandler != null)
return;
DynamicMethod dm = new DynamicMethod("_CreateAndAssing_FH_RT_", MethodAttributes.Static | MethodAttributes.Public, CallingConventions.Standard, typeof(object), new Type[] { typeof(object[]) }, mRecordType, true);
//dm.InitLocals = false;
ILGenerator generator = dm.GetILGenerator();
generator.DeclareLocal(mRecordType);
//generator.DeclareLocal(typeof(object));
generator.Emit(OpCodes.Newobj, mRecordConstructor);
generator.Emit(OpCodes.Stloc_0);
for (int i = 0; i < mFieldCount; i++)
{
FieldBase field = mFields[i];
generator.Emit(OpCodes.Ldloc_0);
generator.Emit(OpCodes.Ldarg_0);
generator.Emit(OpCodes.Ldc_I4, i);
generator.Emit(OpCodes.Ldelem_Ref);
if (field.mFieldType.IsValueType)
{
generator.Emit(OpCodes.Unbox_Any, field.mFieldType);
}
else
{
generator.Emit(OpCodes.Castclass, field.mFieldType);
}
generator.Emit(OpCodes.Stfld, field.mFieldInfo);
//generator.EmitCall();
}
// return the value
generator.Emit(OpCodes.Ldloc_0);
generator.Emit(OpCodes.Ret);
mCreateHandler = (CreateAndAssignCallback)dm.CreateDelegate(typeof(CreateAndAssignCallback));
}
private delegate object CreateNewObject();
private CreateNewObject mFastConstructor;
private void CreateFastConstructor()
{
if (mFastConstructor != null)
return;
DynamicMethod dm = new DynamicMethod("_CreateRecordFast_FH_RT_", MethodAttributes.Static | MethodAttributes.Public, CallingConventions.Standard, typeof(object), new Type[] { typeof(object[]) }, mRecordType, true);
ILGenerator generator = dm.GetILGenerator();
// generator.DeclareLocal(mRecordType);
generator.Emit(OpCodes.Newobj, mRecordConstructor);
generator.Emit(OpCodes.Ret);
mFastConstructor = (CreateNewObject)dm.CreateDelegate(typeof(CreateNewObject));
}
//#endif //NET 2_0
#endregion
#region InitFields
private void InitFields()
{
//-> Checked by the AttributeTargets
//new BadUsageException("Structures are not supported in the FileHelperEngine only classes are allowed.");
TypedRecordAttribute recordAttribute = null;
if (mRecordType.IsDefined(typeof (TypedRecordAttribute), true) == false)
throw new BadUsageException("The class " + mRecordType.Name + " must be marked with the [DelimitedRecord] or [FixedLengthRecord] Attribute.");
else
{
object[] attbs = mRecordType.GetCustomAttributes(typeof (TypedRecordAttribute), true);
recordAttribute = (TypedRecordAttribute) attbs[0];
}
if (mRecordType.GetConstructor(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic, null, mEmptyTypeArr, new ParameterModifier[] {}) == null)
throw new BadUsageException("The record class " + mRecordType.Name + " need a constructor with no args (public or private)");
if (mRecordType.IsDefined(typeof (IgnoreFirstAttribute), false))
mIgnoreFirst = ((IgnoreFirstAttribute) mRecordType.GetCustomAttributes(typeof (IgnoreFirstAttribute), false)[0]).NumberOfLines;
if (mRecordType.IsDefined(typeof (IgnoreLastAttribute), false))
mIgnoreLast = ((IgnoreLastAttribute) mRecordType.GetCustomAttributes(typeof (IgnoreLastAttribute), false)[0]).NumberOfLines;
if (mRecordType.IsDefined(typeof (IgnoreEmptyLinesAttribute), false))
{
mIgnoreEmptyLines = true;
mIgnoreEmptySpaces = ((IgnoreEmptyLinesAttribute) mRecordType.GetCustomAttributes(typeof (IgnoreEmptyLinesAttribute), false)[0]).
mIgnoreSpaces;
}
if (mRecordType.IsDefined(typeof (IgnoreCommentedLinesAttribute), false))
{
IgnoreCommentedLinesAttribute ignoreComments =
(IgnoreCommentedLinesAttribute) mRecordType.GetCustomAttributes(typeof (IgnoreCommentedLinesAttribute), false)[0];
mCommentMarker = ignoreComments.mCommentMarker;
mCommentAnyPlace = ignoreComments.mAnyPlace;
}
if (mRecordType.IsDefined(typeof (ConditionalRecordAttribute), false))
{
ConditionalRecordAttribute conditional =
(ConditionalRecordAttribute) mRecordType.GetCustomAttributes(typeof (ConditionalRecordAttribute), false)[0];
mRecordCondition = conditional.mCondition;
mRecordConditionSelector = conditional.mConditionSelector;
#if ! MINI
if (mRecordCondition == RecordCondition.ExcludeIfMatchRegex ||
mRecordCondition == RecordCondition.IncludeIfMatchRegex)
{
// mConditionRegEx = new Regex(mRecordConditionSelector, RegexOptions.Compiled | RegexOptions.CultureInvariant |RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
mConditionRegEx = new Regex(mRecordConditionSelector, RegexOptions.CultureInvariant | RegexOptions.IgnoreCase | RegexOptions.ExplicitCapture);
}
#endif
}
#if ! MINI
if (typeof(INotifyRead).IsAssignableFrom(mRecordType))
mNotifyRead = true;
if (typeof(INotifyWrite).IsAssignableFrom(mRecordType))
mNotifyWrite = true;
#endif
mRecordConstructor = mRecordType.GetConstructor(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic, null, mEmptyTypeArr, new ParameterModifier[] {});
// Create fields
ArrayList fields = new ArrayList();
RecursiveGetFields(fields, mRecordType, recordAttribute);
mFields = CreateCoreFields(fields, recordAttribute);
mFieldCount = mFields.Length;
if (recordAttribute is FixedLengthRecordAttribute)
{
// Defines the initial size of the StringBuilder
mSizeHint = 0;
for(int i = 0; i < mFieldCount; i++)
mSizeHint += ((FixedLengthField) mFields[i]).mFieldLength;
}
if (mFieldCount == 0)
throw new BadUsageException("The record class " + mRecordType.Name + " don't contains any field.");
}
private void RecursiveGetFields(ArrayList fields, Type currentType, TypedRecordAttribute recordAttribute)
{
if (currentType.BaseType != null)
RecursiveGetFields(fields, currentType.BaseType, recordAttribute);
fields.AddRange(currentType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly));
}
#endregion
#region CreateFields
private static FieldBase[] CreateCoreFields(ArrayList fields, TypedRecordAttribute recordAttribute)
{
FieldBase curField;
ArrayList arr = new ArrayList();
bool someOptional = false;
for (int i = 0; i < fields.Count; i++)
{
FieldInfo fieldInfo = (FieldInfo) fields[i];
curField = FieldFactory.CreateField(fieldInfo, recordAttribute, someOptional);
if (curField != null)
{
someOptional = curField.mIsOptional;
arr.Add(curField);
if (arr.Count > 1)
((FieldBase)arr[arr.Count-2]).mNextIsOptional = ((FieldBase)arr[arr.Count-1]).mIsOptional;
}
}
if (arr.Count > 0)
{
((FieldBase) arr[0]).mIsFirst = true;
((FieldBase) arr[arr.Count - 1]).mIsLast = true;
}
return (FieldBase[]) arr.ToArray(typeof (FieldBase));
}
#endregion
#region GetFieldInfo
internal FieldInfo GetFieldInfo(string name)
{
foreach (FieldBase field in mFields)
{
if (field.mFieldInfo.Name.ToLower() == name.ToLower())
return field.mFieldInfo;
}
return null;
}
#endregion
#region CreateRecordObject
internal object CreateRecordObject()
{
#if NET_2_0
CreateFastConstructor();
if (mFastConstructor == null)
CreateFastConstructor();
return mFastConstructor();
#else
return mRecordConstructor.Invoke(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, RecordInfo.mEmptyObjectArr, null);
#endif
}
#endregion
#region StringToRecord
internal object StringToRecord(LineInfo line)
{
if (MustIgnoreLine(line.mLineStr))
return null;
object[] mValues = new object[mFieldCount];
// array that holds the fields values
for (int i = 0; i < mFieldCount; i++)
{
mValues[i] = mFields[i].ExtractValue(line);
}
#if NET_1_1 || MINI
object record = CreateRecordObject();
for (int i = 0; i < mFieldCount; i++)
{
mFields[i].mFieldInfo.SetValue(record, mValues[i]);
}
return record;
#else
CreateAssingMethods();
try
{
// Asign all values via dinamic method that creates an object and assign values
return mCreateHandler(mValues);
}
catch (InvalidCastException)
{
// Occurrs when the a custom converter returns an invalid value for the field.
for (int i = 0; i < mFieldCount; i++)
{
if (mValues[i] != null && ! mFields[i].mFieldType.IsInstanceOfType(mValues[i]))
throw new ConvertException(null, mFields[i].mFieldType, mFields[i].mFieldInfo.Name, line.mReader.LineNumber, -1, "The converter for the field: " + mFields[i].mFieldInfo.Name + " returns an object of Type: " + mValues[i].GetType().Name + " and the field is of type: " + mFields[i].mFieldType.Name);
}
return null;
}
#endif
}
// private static ErrorManager CreateAndAssign(object[] values)
// {
// ErrorManager record = new ErrorManager();
// record.mErrorMode = (ErrorMode) values[0];
// record.temp = (string) values[1];
//
// return record;
// }
private bool MustIgnoreLine(string line)
{
if (mIgnoreEmptyLines)
if ((mIgnoreEmptySpaces && line.TrimStart().Length == 0) ||
line.Length == 0)
return true;
if (mCommentMarker != null && mCommentMarker.Length > 0)
if ( (mCommentAnyPlace && line.TrimStart().StartsWith(mCommentMarker)) ||
line.StartsWith(mCommentMarker))
return true;
if (mRecordCondition != RecordCondition.None)
{
switch (mRecordCondition)
{
case RecordCondition.ExcludeIfBegins:
return ConditionHelper.BeginsWith(line, mRecordConditionSelector);
case RecordCondition.IncludeIfBegins:
return ! ConditionHelper.BeginsWith(line, mRecordConditionSelector);
case RecordCondition.ExcludeIfContains:
return ConditionHelper.Contains(line, mRecordConditionSelector);
case RecordCondition.IncludeIfContains:
return ConditionHelper.Contains(line, mRecordConditionSelector);
case RecordCondition.ExcludeIfEnclosed:
return ConditionHelper.Enclosed(line, mRecordConditionSelector);
case RecordCondition.IncludeIfEnclosed:
return ! ConditionHelper.Enclosed(line, mRecordConditionSelector);
case RecordCondition.ExcludeIfEnds:
return ConditionHelper.EndsWith(line, mRecordConditionSelector);
case RecordCondition.IncludeIfEnds:
return ! ConditionHelper.EndsWith(line, mRecordConditionSelector);
#if ! MINI
case RecordCondition.ExcludeIfMatchRegex:
return mConditionRegEx.IsMatch(line);
case RecordCondition.IncludeIfMatchRegex:
return ! mConditionRegEx.IsMatch(line);
#endif
}
}
return false;
}
#endregion
#region RecordToString
internal int mSizeHint = 32;
internal string RecordToString(object record)
{
StringBuilder sb = new StringBuilder(mSizeHint);
//string res = String.Empty;
#if NET_1_1 || MINI
object[] mValues = new object[mFieldCount];
for (int i = 0; i < mFieldCount; i++)
{
mValues[i] = mFields[i].mFieldInfo.GetValue(record);
}
#else
CreateGetAllMethod();
object[] mValues = mGetAllValuesHandler(record);
#endif
for (int f = 0; f < mFieldCount; f++)
{
mFields[f].AssignToString(sb, mValues[f]);
}
//_BigSize = Math.Max(_BigSize, sb.Length);
return sb.ToString();
}
#endregion
#region ValuesToRecord
/// <summary>Returns a record formed with the passed values.</summary>
/// <param name="values">The source Values.</param>
/// <returns>A record formed with the passed values.</returns>
public object ValuesToRecord(object[] values)
{
for (int i = 0; i < mFieldCount; i++)
{
if (mFields[i].mFieldType == typeof(DateTime) && values[i] is double)
values[i] = DoubleToDate((int)(double)values[i]);
values[i] = mFields[i].CreateValueForField(values[i]);
}
#if NET_1_1 || MINI
object record = mRecordConstructor.Invoke(RecordInfo.mEmptyObjectArr);
for (int i = 0; i < mFieldCount; i++)
{
mFields[i].mFieldInfo.SetValue(record, values[i]);
}
return record;
#else
CreateAssingMethods();
// Asign all values via dinamic method that creates an object and assign values
return mCreateHandler(values);
#endif
}
private DateTime DoubleToDate(int serialNumber)
{
if (serialNumber < 59)
{
// Because of the 29-02-1900 bug, any serial date
// under 60 is one off... Compensate.
serialNumber++;
}
return new DateTime((serialNumber + 693593) * (10000000L * 24 * 3600));
}
#endregion
#region RecordToValues
/// <summary>Get an object[] of the values in the fields of the passed record.</summary>
/// <param name="record">The source record.</param>
/// <returns>An object[] of the values in the fields.</returns>
public object[] RecordToValues(object record)
{
#if NET_1_1 || MINI
object[] res = new object[mFieldCount];
for (int i = 0; i < mFieldCount; i++)
{
res[i] = mFields[i].mFieldInfo.GetValue(record);
}
return res;
#else
CreateGetAllMethod();
return mGetAllValuesHandler(record);
#endif
}
#endregion
#if ! MINI
#region RecordsToDataTable
internal DataTable RecordsToDataTable(ICollection records)
{
return RecordsToDataTable(records, -1);
}
internal DataTable RecordsToDataTable(ICollection records, int maxRecords)
{
DataTable res = CreateEmptyDataTable();
res.BeginLoadData();
res.MinimumCapacity = records.Count;
if (maxRecords == -1)
{
foreach (object r in records)
res.Rows.Add(RecordToValues(r));
}
else
{
int i = 0;
foreach (object r in records)
{
if (i == maxRecords)
break;
res.Rows.Add(RecordToValues(r));
i++;
}
}
res.EndLoadData();
return res;
}
internal DataTable CreateEmptyDataTable()
{
DataTable res = new DataTable();
foreach (FieldBase f in mFields)
{
DataColumn column1;
column1 = res.Columns.Add(f.mFieldInfo.Name, f.mFieldInfo.FieldType);
column1.ReadOnly = true;
}
return res;
}
#endregion
#endif
#if NET_2_0
public static GetFieldValueCallback CreateGetFieldMethod(FieldInfo fi)
{
DynamicMethod dm = new DynamicMethod("_GetValue"+ fi.Name + "_FH_RT_", MethodAttributes.Static | MethodAttributes.Public, CallingConventions.Standard, typeof(object), new Type[] { typeof(object) }, fi.DeclaringType, true);
ILGenerator generator = dm.GetILGenerator();
generator.Emit(OpCodes.Ldarg_0);
generator.Emit(OpCodes.Castclass, fi.DeclaringType);
generator.Emit(OpCodes.Ldfld, fi);
generator.Emit(OpCodes.Ret);
return (GetFieldValueCallback)dm.CreateDelegate(typeof(GetFieldValueCallback));
}
#endif
}
}

View file

@ -0,0 +1,404 @@
// LumenWorks.Framework.IO.CSV.CachedCsvReader.CsvBindingList
// Copyright (c) 2006 Sébastien Lorion
//
// MIT license (http://en.wikipedia.org/wiki/MIT_License)
//
// 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.
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
namespace LumenWorks.Framework.IO.Csv
{
public partial class CachedCsvReader
: CsvReader
{
/// <summary>
/// Represents a binding list wrapper for a CSV reader.
/// </summary>
private class CsvBindingList
: IBindingList, ITypedList, IList<string[]>, IList
{
#region Fields
/// <summary>
/// Contains the linked CSV reader.
/// </summary>
private CachedCsvReader _csv;
/// <summary>
/// Contains the cached record count.
/// </summary>
private int _count;
/// <summary>
/// Contains the cached property descriptors.
/// </summary>
private PropertyDescriptorCollection _properties;
/// <summary>
/// Contains the current sort property.
/// </summary>
private CsvPropertyDescriptor _sort;
/// <summary>
/// Contains the current sort direction.
/// </summary>
private ListSortDirection _direction;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the CsvBindingList class.
/// </summary>
/// <param name="csv"></param>
public CsvBindingList(CachedCsvReader csv)
{
_csv = csv;
_count = -1;
_direction = ListSortDirection.Ascending;
}
#endregion
#region IBindingList members
public void AddIndex(PropertyDescriptor property)
{
}
public bool AllowNew
{
get
{
return false;
}
}
public void ApplySort(PropertyDescriptor property, System.ComponentModel.ListSortDirection direction)
{
_sort = (CsvPropertyDescriptor) property;
_direction = direction;
_csv.ReadToEnd();
_csv._records.Sort(new CsvRecordComparer(_sort.Index, _direction));
}
public PropertyDescriptor SortProperty
{
get
{
return _sort;
}
}
public int Find(PropertyDescriptor property, object key)
{
int fieldIndex = ((CsvPropertyDescriptor) property).Index;
string value = (string) key;
int recordIndex = 0;
int count = this.Count;
while (recordIndex < count && _csv[recordIndex, fieldIndex] != value)
recordIndex++;
if (recordIndex == count)
return -1;
else
return recordIndex;
}
public bool SupportsSorting
{
get
{
return true;
}
}
public bool IsSorted
{
get
{
return _sort != null;
}
}
public bool AllowRemove
{
get
{
return false;
}
}
public bool SupportsSearching
{
get
{
return true;
}
}
public System.ComponentModel.ListSortDirection SortDirection
{
get
{
return _direction;
}
}
public event System.ComponentModel.ListChangedEventHandler ListChanged
{
add { }
remove { }
}
public bool SupportsChangeNotification
{
get
{
return false;
}
}
public void RemoveSort()
{
_sort = null;
_direction = ListSortDirection.Ascending;
}
public object AddNew()
{
throw new NotSupportedException();
}
public bool AllowEdit
{
get
{
return false;
}
}
public void RemoveIndex(PropertyDescriptor property)
{
}
#endregion
#region ITypedList Members
public PropertyDescriptorCollection GetItemProperties(PropertyDescriptor[] listAccessors)
{
if (_properties == null)
{
PropertyDescriptor[] properties = new PropertyDescriptor[_csv.FieldCount];
for (int i = 0; i < properties.Length; i++)
properties[i] = new CsvPropertyDescriptor(((System.Data.IDataReader) _csv).GetName(i), i);
_properties = new PropertyDescriptorCollection(properties);
}
return _properties;
}
public string GetListName(PropertyDescriptor[] listAccessors)
{
return string.Empty;
}
#endregion
#region IList<string[]> Members
public int IndexOf(string[] item)
{
throw new NotSupportedException();
}
public void Insert(int index, string[] item)
{
throw new NotSupportedException();
}
public void RemoveAt(int index)
{
throw new NotSupportedException();
}
public string[] this[int index]
{
get
{
_csv.MoveTo(index);
return _csv._records[index];
}
set
{
throw new NotSupportedException();
}
}
#endregion
#region ICollection<string[]> Members
public void Add(string[] item)
{
throw new NotSupportedException();
}
public void Clear()
{
throw new NotSupportedException();
}
public bool Contains(string[] item)
{
throw new NotSupportedException();
}
public void CopyTo(string[][] array, int arrayIndex)
{
_csv.MoveToStart();
while (_csv.ReadNextRecord())
_csv.CopyCurrentRecordTo(array[arrayIndex++]);
}
public int Count
{
get
{
if (_count < 0)
{
_csv.ReadToEnd();
_count = (int) _csv.CurrentRecordIndex + 1;
}
return _count;
}
}
public bool IsReadOnly
{
get { return true; }
}
public bool Remove(string[] item)
{
throw new NotSupportedException();
}
#endregion
#region IEnumerable<string[]> Members
public IEnumerator<string[]> GetEnumerator()
{
return _csv.GetEnumerator();
}
#endregion
#region IList Members
public int Add(object value)
{
throw new NotSupportedException();
}
public bool Contains(object value)
{
throw new NotSupportedException();
}
public int IndexOf(object value)
{
throw new NotSupportedException();
}
public void Insert(int index, object value)
{
throw new NotSupportedException();
}
public bool IsFixedSize
{
get { return true; }
}
public void Remove(object value)
{
throw new NotSupportedException();
}
object IList.this[int index]
{
get
{
return this[index];
}
set
{
throw new NotSupportedException();
}
}
#endregion
#region ICollection Members
public void CopyTo(Array array, int index)
{
_csv.MoveToStart();
while (_csv.ReadNextRecord())
_csv.CopyCurrentRecordTo((string[]) array.GetValue(index++));
}
public bool IsSynchronized
{
get { return false; }
}
public object SyncRoot
{
get { return null; }
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
}
}
}

View file

@ -0,0 +1,126 @@
// LumenWorks.Framework.IO.CSV.CachedCsvReader.CsvPropertyDescriptor
// Copyright (c) 2006 Sébastien Lorion
//
// MIT license (http://en.wikipedia.org/wiki/MIT_License)
//
// 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.
using System;
using System.Collections.Generic;
using System.ComponentModel;
namespace LumenWorks.Framework.IO.Csv
{
public partial class CachedCsvReader
: CsvReader
{
/// <summary>
/// Represents a CSV field property descriptor.
/// </summary>
private class CsvPropertyDescriptor
: PropertyDescriptor
{
#region Fields
/// <summary>
/// Contains the field index.
/// </summary>
private int _index;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the CsvPropertyDescriptor class.
/// </summary>
/// <param name="fieldName">The field name.</param>
/// <param name="index">The field index.</param>
public CsvPropertyDescriptor(string fieldName, int index)
: base(fieldName, null)
{
_index = index;
}
#endregion
#region Properties
/// <summary>
/// Gets the field index.
/// </summary>
/// <value>The field index.</value>
public int Index
{
get { return _index; }
}
#endregion
#region Overrides
public override bool CanResetValue(object component)
{
return false;
}
public override object GetValue(object component)
{
return ((string[]) component)[_index];
}
public override void ResetValue(object component)
{
}
public override void SetValue(object component, object value)
{
}
public override bool ShouldSerializeValue(object component)
{
return false;
}
public override Type ComponentType
{
get
{
return typeof(CachedCsvReader);
}
}
public override bool IsReadOnly
{
get
{
return true;
}
}
public override Type PropertyType
{
get
{
return typeof(string);
}
}
#endregion
}
}
}

View file

@ -0,0 +1,85 @@
// LumenWorks.Framework.IO.CSV.CachedCsvReader.CsvRecordComparer
// Copyright (c) 2006 Sébastien Lorion
//
// MIT license (http://en.wikipedia.org/wiki/MIT_License)
//
// 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.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using Debug = System.Diagnostics.Debug;
using System.Globalization;
namespace LumenWorks.Framework.IO.Csv
{
public partial class CachedCsvReader
: CsvReader
{
/// <summary>
/// Represents a CSV record comparer.
/// </summary>
private class CsvRecordComparer
: IComparer<string[]>
{
#region Fields
/// <summary>
/// Contains the field index of the values to compare.
/// </summary>
private int _field;
/// <summary>
/// Contains the sort direction.
/// </summary>
private ListSortDirection _direction;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the CsvRecordComparer class.
/// </summary>
/// <param name="field">The field index of the values to compare.</param>
/// <param name="direction">The sort direction.</param>
public CsvRecordComparer(int field, ListSortDirection direction)
{
if (field < 0)
throw new ArgumentOutOfRangeException("field", field, string.Format(CultureInfo.InvariantCulture, Resources.ExceptionMessage.FieldIndexOutOfRange, field));
_field = field;
_direction = direction;
}
#endregion
#region IComparer<string[]> Members
public int Compare(string[] x, string[] y)
{
Debug.Assert(x != null && y != null && x.Length == y.Length && _field < x.Length);
int result = String.Compare(x[_field], y[_field], StringComparison.CurrentCulture);
return (_direction == ListSortDirection.Ascending ? result : -result);
}
#endregion
}
}
}

View file

@ -0,0 +1,410 @@
// LumenWorks.Framework.IO.CSV.CachedCsvReader
// Copyright (c) 2005 Sébastien Lorion
//
// MIT license (http://en.wikipedia.org/wiki/MIT_License)
//
// 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.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using LumenWorks.Framework.IO.Csv.Resources;
namespace LumenWorks.Framework.IO.Csv
{
/// <summary>
/// Represents a reader that provides fast, cached, dynamic access to CSV data.
/// </summary>
/// <remarks>The number of records is limited to <see cref="System.Int32.MaxValue"/> - 1.</remarks>
public partial class CachedCsvReader
: CsvReader, IListSource
{
#region Fields
/// <summary>
/// Contains the cached records.
/// </summary>
private List<string[]> _records;
/// <summary>
/// Contains the current record index (inside the cached records array).
/// </summary>
private long _currentRecordIndex;
/// <summary>
/// Indicates if a new record is being read from the CSV stream.
/// </summary>
private bool _readingStream;
/// <summary>
/// Contains the binding list linked to this reader.
/// </summary>
private CsvBindingList _bindingList;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the CsvReader class.
/// </summary>
/// <param name="reader">A <see cref="T:TextReader"/> pointing to the CSV file.</param>
/// <param name="hasHeaders"><see langword="true"/> if field names are located on the first non commented line, otherwise, <see langword="false"/>.</param>
/// <exception cref="T:ArgumentNullException">
/// <paramref name="reader"/> is a <see langword="null"/>.
/// </exception>
/// <exception cref="T:ArgumentException">
/// Cannot read from <paramref name="reader"/>.
/// </exception>
public CachedCsvReader(TextReader reader, bool hasHeaders)
: this(reader, hasHeaders, DefaultBufferSize)
{
}
/// <summary>
/// Initializes a new instance of the CsvReader class.
/// </summary>
/// <param name="reader">A <see cref="T:TextReader"/> pointing to the CSV file.</param>
/// <param name="hasHeaders"><see langword="true"/> if field names are located on the first non commented line, otherwise, <see langword="false"/>.</param>
/// <param name="bufferSize">The buffer size in bytes.</param>
/// <exception cref="T:ArgumentNullException">
/// <paramref name="reader"/> is a <see langword="null"/>.
/// </exception>
/// <exception cref="T:ArgumentException">
/// Cannot read from <paramref name="reader"/>.
/// </exception>
public CachedCsvReader(TextReader reader, bool hasHeaders, int bufferSize)
: this(reader, hasHeaders, DefaultDelimiter, DefaultQuote, DefaultEscape, DefaultComment, ValueTrimmingOptions.UnquotedOnly, bufferSize)
{
}
/// <summary>
/// Initializes a new instance of the CsvReader class.
/// </summary>
/// <param name="reader">A <see cref="T:TextReader"/> pointing to the CSV file.</param>
/// <param name="hasHeaders"><see langword="true"/> if field names are located on the first non commented line, otherwise, <see langword="false"/>.</param>
/// <param name="delimiter">The delimiter character separating each field (default is ',').</param>
/// <exception cref="T:ArgumentNullException">
/// <paramref name="reader"/> is a <see langword="null"/>.
/// </exception>
/// <exception cref="T:ArgumentException">
/// Cannot read from <paramref name="reader"/>.
/// </exception>
public CachedCsvReader(TextReader reader, bool hasHeaders, char delimiter)
: this(reader, hasHeaders, delimiter, DefaultQuote, DefaultEscape, DefaultComment, ValueTrimmingOptions.UnquotedOnly, DefaultBufferSize)
{
}
/// <summary>
/// Initializes a new instance of the CsvReader class.
/// </summary>
/// <param name="reader">A <see cref="T:TextReader"/> pointing to the CSV file.</param>
/// <param name="hasHeaders"><see langword="true"/> if field names are located on the first non commented line, otherwise, <see langword="false"/>.</param>
/// <param name="delimiter">The delimiter character separating each field (default is ',').</param>
/// <param name="bufferSize">The buffer size in bytes.</param>
/// <exception cref="T:ArgumentNullException">
/// <paramref name="reader"/> is a <see langword="null"/>.
/// </exception>
/// <exception cref="T:ArgumentException">
/// Cannot read from <paramref name="reader"/>.
/// </exception>
public CachedCsvReader(TextReader reader, bool hasHeaders, char delimiter, int bufferSize)
: this(reader, hasHeaders, delimiter, DefaultQuote, DefaultEscape, DefaultComment, ValueTrimmingOptions.UnquotedOnly, bufferSize)
{
}
/// <summary>
/// Initializes a new instance of the CsvReader class.
/// </summary>
/// <param name="reader">A <see cref="T:TextReader"/> pointing to the CSV file.</param>
/// <param name="hasHeaders"><see langword="true"/> if field names are located on the first non commented line, otherwise, <see langword="false"/>.</param>
/// <param name="delimiter">The delimiter character separating each field (default is ',').</param>
/// <param name="quote">The quotation character wrapping every field (default is ''').</param>
/// <param name="escape">
/// The escape character letting insert quotation characters inside a quoted field (default is '\').
/// If no escape character, set to '\0' to gain some performance.
/// </param>
/// <param name="comment">The comment character indicating that a line is commented out (default is '#').</param>
/// <param name="trimmingOptions">Determines how values should be trimmed.</param>
/// <exception cref="T:ArgumentNullException">
/// <paramref name="reader"/> is a <see langword="null"/>.
/// </exception>
/// <exception cref="T:ArgumentException">
/// Cannot read from <paramref name="reader"/>.
/// </exception>
public CachedCsvReader(TextReader reader, bool hasHeaders, char delimiter, char quote, char escape, char comment, ValueTrimmingOptions trimmingOptions)
: this(reader, hasHeaders, delimiter, quote, escape, comment, trimmingOptions, DefaultBufferSize)
{
}
/// <summary>
/// Initializes a new instance of the CsvReader class.
/// </summary>
/// <param name="reader">A <see cref="T:TextReader"/> pointing to the CSV file.</param>
/// <param name="hasHeaders"><see langword="true"/> if field names are located on the first non commented line, otherwise, <see langword="false"/>.</param>
/// <param name="delimiter">The delimiter character separating each field (default is ',').</param>
/// <param name="quote">The quotation character wrapping every field (default is ''').</param>
/// <param name="escape">
/// The escape character letting insert quotation characters inside a quoted field (default is '\').
/// If no escape character, set to '\0' to gain some performance.
/// </param>
/// <param name="comment">The comment character indicating that a line is commented out (default is '#').</param>
/// <param name="trimSpaces"><see langword="true"/> if spaces at the start and end of a field are trimmed, otherwise, <see langword="false"/>. Default is <see langword="true"/>.</param>
/// <param name="bufferSize">The buffer size in bytes.</param>
/// <exception cref="T:ArgumentNullException">
/// <paramref name="reader"/> is a <see langword="null"/>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="bufferSize"/> must be 1 or more.
/// </exception>
public CachedCsvReader(TextReader reader, bool hasHeaders, char delimiter, char quote, char escape, char comment, ValueTrimmingOptions trimmingOptions, int bufferSize)
: base(reader, hasHeaders, delimiter, quote, escape, comment, trimmingOptions, bufferSize)
{
_records = new List<string[]>();
_currentRecordIndex = -1;
}
#endregion
#region Properties
#region State
/// <summary>
/// Gets the current record index in the CSV file.
/// </summary>
/// <value>The current record index in the CSV file.</value>
public override long CurrentRecordIndex
{
get
{
return _currentRecordIndex;
}
}
/// <summary>
/// Gets a value that indicates whether the current stream position is at the end of the stream.
/// </summary>
/// <value><see langword="true"/> if the current stream position is at the end of the stream; otherwise <see langword="false"/>.</value>
public override bool EndOfStream
{
get
{
if (_currentRecordIndex < base.CurrentRecordIndex)
return false;
else
return base.EndOfStream;
}
}
#endregion
#endregion
#region Indexers
/// <summary>
/// Gets the field at the specified index.
/// </summary>
/// <value>The field at the specified index.</value>
/// <exception cref="T:ArgumentOutOfRangeException">
/// <paramref name="field"/> must be included in [0, <see cref="M:FieldCount"/>[.
/// </exception>
/// <exception cref="T:InvalidOperationException">
/// No record read yet. Call ReadLine() first.
/// </exception>
/// <exception cref="MissingFieldCsvException">
/// The CSV data appears to be missing a field.
/// </exception>
/// <exception cref="T:MalformedCsvException">
/// The CSV appears to be corrupt at the current position.
/// </exception>
/// <exception cref="T:System.ComponentModel.ObjectDisposedException">
/// The instance has been disposed of.
/// </exception>
public override String this[int field]
{
get
{
if (_readingStream)
return base[field];
else if (_currentRecordIndex > -1)
{
if (field > -1 && field < this.FieldCount)
return _records[(int) _currentRecordIndex][field];
else
throw new ArgumentOutOfRangeException("field", field, string.Format(CultureInfo.InvariantCulture, ExceptionMessage.FieldIndexOutOfRange, field));
}
else
throw new InvalidOperationException(ExceptionMessage.NoCurrentRecord);
}
}
#endregion
#region Methods
#region Read
/// <summary>
/// Reads the CSV stream from the current position to the end of the stream.
/// </summary>
/// <exception cref="T:System.ComponentModel.ObjectDisposedException">
/// The instance has been disposed of.
/// </exception>
public virtual void ReadToEnd()
{
_currentRecordIndex = base.CurrentRecordIndex;
while (ReadNextRecord()) ;
}
/// <summary>
/// Reads the next record.
/// </summary>
/// <param name="onlyReadHeaders">
/// Indicates if the reader will proceed to the next record after having read headers.
/// <see langword="true"/> if it stops after having read headers; otherwise, <see langword="false"/>.
/// </param>
/// <param name="skipToNextLine">
/// Indicates if the reader will skip directly to the next line without parsing the current one.
/// To be used when an error occurs.
/// </param>
/// <returns><see langword="true"/> if a record has been successfully reads; otherwise, <see langword="false"/>.</returns>
/// <exception cref="T:System.ComponentModel.ObjectDisposedException">
/// The instance has been disposed of.
/// </exception>
protected override bool ReadNextRecord(bool onlyReadHeaders, bool skipToNextLine)
{
if (_currentRecordIndex < base.CurrentRecordIndex)
{
_currentRecordIndex++;
return true;
}
else
{
_readingStream = true;
try
{
bool canRead = base.ReadNextRecord(onlyReadHeaders, skipToNextLine);
if (canRead)
{
string[] record = new string[this.FieldCount];
if (base.CurrentRecordIndex > -1)
{
CopyCurrentRecordTo(record);
_records.Add(record);
}
else
{
if (MoveTo(0))
CopyCurrentRecordTo(record);
MoveTo(-1);
}
if (!onlyReadHeaders)
_currentRecordIndex++;
}
else
{
// No more records to read, so set array size to only what is needed
_records.Capacity = _records.Count;
}
return canRead;
}
finally
{
_readingStream = false;
}
}
}
#endregion
#region Move
/// <summary>
/// Moves before the first record.
/// </summary>
public void MoveToStart()
{
_currentRecordIndex = -1;
}
/// <summary>
/// Moves to the last record read so far.
/// </summary>
public void MoveToLastCachedRecord()
{
_currentRecordIndex = base.CurrentRecordIndex;
}
/// <summary>
/// Moves to the specified record index.
/// </summary>
/// <param name="record">The record index.</param>
/// <returns><c>true</c> if the operation was successful; otherwise, <c>false</c>.</returns>
/// <exception cref="T:System.ComponentModel.ObjectDisposedException">
/// The instance has been disposed of.
/// </exception>
public override bool MoveTo(long record)
{
if (record < -1)
record = -1;
if (record <= base.CurrentRecordIndex)
{
_currentRecordIndex = record;
return true;
}
else
{
_currentRecordIndex = base.CurrentRecordIndex;
return base.MoveTo(record);
}
}
#endregion
#endregion
#region IListSource Members
bool IListSource.ContainsListCollection
{
get { return false; }
}
System.Collections.IList IListSource.GetList()
{
if (_bindingList == null)
_bindingList = new CsvBindingList(this);
return _bindingList;
}
#endregion
}
}

View file

@ -0,0 +1,50 @@
// LumenWorks.Framework.IO.CSV.CsvReader.DataReaderValidations
// Copyright (c) 2005 Sébastien Lorion
//
// MIT license (http://en.wikipedia.org/wiki/MIT_License)
//
// 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.
using System;
namespace LumenWorks.Framework.IO.Csv
{
public partial class CsvReader
{
/// <summary>
/// Defines the data reader validations.
/// </summary>
[Flags]
private enum DataReaderValidations
{
/// <summary>
/// No validation.
/// </summary>
None = 0,
/// <summary>
/// Validate that the data reader is initialized.
/// </summary>
IsInitialized = 1,
/// <summary>
/// Validate that the data reader is not closed.
/// </summary>
IsNotClosed = 2
}
}
}

View file

@ -0,0 +1,164 @@
// LumenWorks.Framework.IO.CSV.CsvReader.RecordEnumerator
// Copyright (c) 2005 Sébastien Lorion
//
// MIT license (http://en.wikipedia.org/wiki/MIT_License)
//
// 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.
using System;
using System.Collections;
using System.Collections.Generic;
using LumenWorks.Framework.IO.Csv.Resources;
namespace LumenWorks.Framework.IO.Csv
{
public partial class CsvReader
{
/// <summary>
/// Supports a simple iteration over the records of a <see cref="T:CsvReader"/>.
/// </summary>
public struct RecordEnumerator
: IEnumerator<string[]>, IEnumerator
{
#region Fields
/// <summary>
/// Contains the enumerated <see cref="T:CsvReader"/>.
/// </summary>
private CsvReader _reader;
/// <summary>
/// Contains the current record.
/// </summary>
private string[] _current;
/// <summary>
/// Contains the current record index.
/// </summary>
private long _currentRecordIndex;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="T:RecordEnumerator"/> class.
/// </summary>
/// <param name="reader">The <see cref="T:CsvReader"/> to iterate over.</param>
/// <exception cref="T:ArgumentNullException">
/// <paramref name="reader"/> is a <see langword="null"/>.
/// </exception>
public RecordEnumerator(CsvReader reader)
{
if (reader == null)
throw new ArgumentNullException("reader");
_reader = reader;
_current = null;
_currentRecordIndex = reader._currentRecordIndex;
}
#endregion
#region IEnumerator<string[]> Members
/// <summary>
/// Gets the current record.
/// </summary>
public string[] Current
{
get { return _current; }
}
/// <summary>
/// Advances the enumerator to the next record of the CSV.
/// </summary>
/// <returns><see langword="true"/> if the enumerator was successfully advanced to the next record, <see langword="false"/> if the enumerator has passed the end of the CSV.</returns>
public bool MoveNext()
{
if (_reader._currentRecordIndex != _currentRecordIndex)
throw new InvalidOperationException(ExceptionMessage.EnumerationVersionCheckFailed);
if (_reader.ReadNextRecord())
{
_current = new string[_reader._fieldCount];
_reader.CopyCurrentRecordTo(_current);
_currentRecordIndex = _reader._currentRecordIndex;
return true;
}
else
{
_current = null;
_currentRecordIndex = _reader._currentRecordIndex;
return false;
}
}
#endregion
#region IEnumerator Members
/// <summary>
/// Sets the enumerator to its initial position, which is before the first record in the CSV.
/// </summary>
public void Reset()
{
if (_reader._currentRecordIndex != _currentRecordIndex)
throw new InvalidOperationException(ExceptionMessage.EnumerationVersionCheckFailed);
_reader.MoveTo(-1);
_current = null;
_currentRecordIndex = _reader._currentRecordIndex;
}
/// <summary>
/// Gets the current record.
/// </summary>
object IEnumerator.Current
{
get
{
if (_reader._currentRecordIndex != _currentRecordIndex)
throw new InvalidOperationException(ExceptionMessage.EnumerationVersionCheckFailed);
return this.Current;
}
}
#endregion
#region IDisposable Members
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
_reader = null;
_current = null;
}
#endregion
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,85 @@
// LumenWorks.Framework.IO.CSV.ParseErrorEventArgs
// Copyright (c) 2006 Sébastien Lorion
//
// MIT license (http://en.wikipedia.org/wiki/MIT_License)
//
// 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.
using System;
namespace LumenWorks.Framework.IO.Csv
{
/// <summary>
/// Provides data for the <see cref="M:CsvReader.ParseError"/> event.
/// </summary>
public class ParseErrorEventArgs
: EventArgs
{
#region Fields
/// <summary>
/// Contains the error that occured.
/// </summary>
private MalformedCsvException _error;
/// <summary>
/// Contains the action to take.
/// </summary>
private ParseErrorAction _action;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the ParseErrorEventArgs class.
/// </summary>
/// <param name="error">The error that occured.</param>
/// <param name="defaultAction">The default action to take.</param>
public ParseErrorEventArgs(MalformedCsvException error, ParseErrorAction defaultAction)
: base()
{
_error = error;
_action = defaultAction;
}
#endregion
#region Properties
/// <summary>
/// Gets the error that occured.
/// </summary>
/// <value>The error that occured.</value>
public MalformedCsvException Error
{
get { return _error; }
}
/// <summary>
/// Gets or sets the action to take.
/// </summary>
/// <value>The action to take.</value>
public ParseErrorAction Action
{
get { return _action; }
set { _action = value; }
}
#endregion
}
}

View file

@ -0,0 +1,221 @@
// LumenWorks.Framework.IO.Csv.MalformedCsvException
// Copyright (c) 2005 Sébastien Lorion
//
// MIT license (http://en.wikipedia.org/wiki/MIT_License)
//
// 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.
using System;
using System.Globalization;
using System.Runtime.Serialization;
using System.Security.Permissions;
using LumenWorks.Framework.IO.Csv.Resources;
namespace LumenWorks.Framework.IO.Csv
{
/// <summary>
/// Represents the exception that is thrown when a CSV file is malformed.
/// </summary>
[Serializable()]
public class MalformedCsvException
: Exception
{
#region Fields
/// <summary>
/// Contains the message that describes the error.
/// </summary>
private string _message;
/// <summary>
/// Contains the raw data when the error occured.
/// </summary>
private string _rawData;
/// <summary>
/// Contains the current field index.
/// </summary>
private int _currentFieldIndex;
/// <summary>
/// Contains the current record index.
/// </summary>
private long _currentRecordIndex;
/// <summary>
/// Contains the current position in the raw data.
/// </summary>
private int _currentPosition;
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the MalformedCsvException class.
/// </summary>
public MalformedCsvException()
: this(null, null)
{
}
/// <summary>
/// Initializes a new instance of the MalformedCsvException class.
/// </summary>
/// <param name="message">The message that describes the error.</param>
public MalformedCsvException(string message)
: this(message, null)
{
}
/// <summary>
/// Initializes a new instance of the MalformedCsvException class.
/// </summary>
/// <param name="message">The message that describes the error.</param>
/// <param name="innerException">The exception that is the cause of the current exception.</param>
public MalformedCsvException(string message, Exception innerException)
: base(String.Empty, innerException)
{
_message = (message == null ? string.Empty : message);
_rawData = string.Empty;
_currentPosition = -1;
_currentRecordIndex = -1;
_currentFieldIndex = -1;
}
/// <summary>
/// Initializes a new instance of the MalformedCsvException class.
/// </summary>
/// <param name="rawData">The raw data when the error occured.</param>
/// <param name="currentPosition">The current position in the raw data.</param>
/// <param name="currentRecordIndex">The current record index.</param>
/// <param name="currentFieldIndex">The current field index.</param>
public MalformedCsvException(string rawData, int currentPosition, long currentRecordIndex, int currentFieldIndex)
: this(rawData, currentPosition, currentRecordIndex, currentFieldIndex, null)
{
}
/// <summary>
/// Initializes a new instance of the MalformedCsvException class.
/// </summary>
/// <param name="rawData">The raw data when the error occured.</param>
/// <param name="currentPosition">The current position in the raw data.</param>
/// <param name="currentRecordIndex">The current record index.</param>
/// <param name="currentFieldIndex">The current field index.</param>
/// <param name="innerException">The exception that is the cause of the current exception.</param>
public MalformedCsvException(string rawData, int currentPosition, long currentRecordIndex, int currentFieldIndex, Exception innerException)
: base(String.Empty, innerException)
{
_rawData = (rawData == null ? string.Empty : rawData);
_currentPosition = currentPosition;
_currentRecordIndex = currentRecordIndex;
_currentFieldIndex = currentFieldIndex;
_message = String.Format(CultureInfo.InvariantCulture, ExceptionMessage.MalformedCsvException, _currentRecordIndex, _currentFieldIndex, _currentPosition, _rawData);
}
/// <summary>
/// Initializes a new instance of the MalformedCsvException class with serialized data.
/// </summary>
/// <param name="info">The <see cref="T:SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:StreamingContext"/> that contains contextual information about the source or destination.</param>
protected MalformedCsvException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
_message = info.GetString("MyMessage");
_rawData = info.GetString("RawData");
_currentPosition = info.GetInt32("CurrentPosition");
_currentRecordIndex = info.GetInt64("CurrentRecordIndex");
_currentFieldIndex = info.GetInt32("CurrentFieldIndex");
}
#endregion
#region Properties
/// <summary>
/// Gets the raw data when the error occured.
/// </summary>
/// <value>The raw data when the error occured.</value>
public string RawData
{
get { return _rawData; }
}
/// <summary>
/// Gets the current position in the raw data.
/// </summary>
/// <value>The current position in the raw data.</value>
public int CurrentPosition
{
get { return _currentPosition; }
}
/// <summary>
/// Gets the current record index.
/// </summary>
/// <value>The current record index.</value>
public long CurrentRecordIndex
{
get { return _currentRecordIndex; }
}
/// <summary>
/// Gets the current field index.
/// </summary>
/// <value>The current record index.</value>
public int CurrentFieldIndex
{
get { return _currentFieldIndex; }
}
#endregion
#region Overrides
/// <summary>
/// Gets a message that describes the current exception.
/// </summary>
/// <value>A message that describes the current exception.</value>
public override string Message
{
get { return _message; }
}
/// <summary>
/// When overridden in a derived class, sets the <see cref="T:SerializationInfo"/> with information about the exception.
/// </summary>
/// <param name="info">The <see cref="T:SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:StreamingContext"/> that contains contextual information about the source or destination.</param>
public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
{
base.GetObjectData(info, context);
info.AddValue("MyMessage", _message);
info.AddValue("RawData", _rawData);
info.AddValue("CurrentPosition", _currentPosition);
info.AddValue("CurrentRecordIndex", _currentRecordIndex);
info.AddValue("CurrentFieldIndex", _currentFieldIndex);
}
#endregion
}
}

View file

@ -0,0 +1,107 @@
// LumenWorks.Framework.IO.Csv.MissingFieldCsvException
// Copyright (c) 2005 Sébastien Lorion
//
// MIT license (http://en.wikipedia.org/wiki/MIT_License)
//
// 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.
using System;
using System.Globalization;
using System.Runtime.Serialization;
using System.Security.Permissions;
using LumenWorks.Framework.IO.Csv.Resources;
namespace LumenWorks.Framework.IO.Csv
{
/// <summary>
/// Represents the exception that is thrown when a there is a missing field in a record of the CSV file.
/// </summary>
/// <remarks>
/// MissingFieldException would have been a better name, but there is already a <see cref="T:System.MissingFieldException"/>.
/// </remarks>
[Serializable()]
public class MissingFieldCsvException
: MalformedCsvException
{
#region Constructors
/// <summary>
/// Initializes a new instance of the MissingFieldCsvException class.
/// </summary>
public MissingFieldCsvException()
: base()
{
}
/// <summary>
/// Initializes a new instance of the MissingFieldCsvException class.
/// </summary>
/// <param name="message">The message that describes the error.</param>
public MissingFieldCsvException(string message)
: base(message)
{
}
/// <summary>
/// Initializes a new instance of the MissingFieldCsvException class.
/// </summary>
/// <param name="message">The message that describes the error.</param>
/// <param name="innerException">The exception that is the cause of the current exception.</param>
public MissingFieldCsvException(string message, Exception innerException)
: base(message, innerException)
{
}
/// <summary>
/// Initializes a new instance of the MissingFieldCsvException class.
/// </summary>
/// <param name="rawData">The raw data when the error occured.</param>
/// <param name="currentPosition">The current position in the raw data.</param>
/// <param name="currentRecordIndex">The current record index.</param>
/// <param name="currentFieldIndex">The current field index.</param>
public MissingFieldCsvException(string rawData, int currentPosition, long currentRecordIndex, int currentFieldIndex)
: base(rawData, currentPosition, currentRecordIndex, currentFieldIndex)
{
}
/// <summary>
/// Initializes a new instance of the MissingFieldCsvException class.
/// </summary>
/// <param name="rawData">The raw data when the error occured.</param>
/// <param name="currentPosition">The current position in the raw data.</param>
/// <param name="currentRecordIndex">The current record index.</param>
/// <param name="currentFieldIndex">The current field index.</param>
/// <param name="innerException">The exception that is the cause of the current exception.</param>
public MissingFieldCsvException(string rawData, int currentPosition, long currentRecordIndex, int currentFieldIndex, Exception innerException)
: base(rawData, currentPosition, currentRecordIndex, currentFieldIndex, innerException)
{
}
/// <summary>
/// Initializes a new instance of the MissingFieldCsvException class with serialized data.
/// </summary>
/// <param name="info">The <see cref="T:SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:StreamingContext"/> that contains contextual information about the source or destination.</param>
protected MissingFieldCsvException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
#endregion
}
}

View file

@ -0,0 +1,46 @@
// LumenWorks.Framework.IO.CSV.MissingFieldAction
// Copyright (c) 2006 Sébastien Lorion
//
// MIT license (http://en.wikipedia.org/wiki/MIT_License)
//
// 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.
using System;
namespace LumenWorks.Framework.IO.Csv
{
/// <summary>
/// Specifies the action to take when a field is missing.
/// </summary>
public enum MissingFieldAction
{
/// <summary>
/// Treat as a parsing error.
/// </summary>
ParseError = 0,
/// <summary>
/// Replaces by an empty value.
/// </summary>
ReplaceByEmpty = 1,
/// <summary>
/// Replaces by a null value (<see langword="null"/>).
/// </summary>
ReplaceByNull = 2,
}
}

View file

@ -0,0 +1,46 @@
// LumenWorks.Framework.IO.CSV.ParseErrorAction
// Copyright (c) 2006 Sébastien Lorion
//
// MIT license (http://en.wikipedia.org/wiki/MIT_License)
//
// 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.
using System;
namespace LumenWorks.Framework.IO.Csv
{
/// <summary>
/// Specifies the action to take when a parsing error has occured.
/// </summary>
public enum ParseErrorAction
{
/// <summary>
/// Raises the <see cref="M:CsvReader.ParseError"/> event.
/// </summary>
RaiseEvent = 0,
/// <summary>
/// Tries to advance to next line.
/// </summary>
AdvanceToNextLine = 1,
/// <summary>
/// Throws an exception.
/// </summary>
ThrowException = 2,
}
}

View file

@ -0,0 +1,207 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.42
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace LumenWorks.Framework.IO.Csv.Resources {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class ExceptionMessage {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal ExceptionMessage() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("LumenWorks.Framework.IO.Csv.Resources.ExceptionMessage", typeof(ExceptionMessage).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to Buffer size must be 1 or more..
/// </summary>
internal static string BufferSizeTooSmall {
get {
return ResourceManager.GetString("BufferSizeTooSmall", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cannot move to a previous record in forward-only mode..
/// </summary>
internal static string CannotMovePreviousRecordInForwardOnly {
get {
return ResourceManager.GetString("CannotMovePreviousRecordInForwardOnly", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cannot read record at index &apos;{0}&apos;..
/// </summary>
internal static string CannotReadRecordAtIndex {
get {
return ResourceManager.GetString("CannotReadRecordAtIndex", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Enumeration has either not started or has already finished..
/// </summary>
internal static string EnumerationFinishedOrNotStarted {
get {
return ResourceManager.GetString("EnumerationFinishedOrNotStarted", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Collection was modified; enumeration operation may not execute..
/// </summary>
internal static string EnumerationVersionCheckFailed {
get {
return ResourceManager.GetString("EnumerationVersionCheckFailed", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &apos;{0}&apos; field header not found..
/// </summary>
internal static string FieldHeaderNotFound {
get {
return ResourceManager.GetString("FieldHeaderNotFound", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Field index must be included in [0, FieldCount[. Specified field index was : &apos;{0}&apos;..
/// </summary>
internal static string FieldIndexOutOfRange {
get {
return ResourceManager.GetString("FieldIndexOutOfRange", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The CSV appears to be corrupt near record &apos;{0}&apos; field &apos;{1} at position &apos;{2}&apos;. Current raw data : &apos;{3}&apos;..
/// </summary>
internal static string MalformedCsvException {
get {
return ResourceManager.GetString("MalformedCsvException", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &apos;{0}&apos; is not a supported missing field action..
/// </summary>
internal static string MissingFieldActionNotSupported {
get {
return ResourceManager.GetString("MissingFieldActionNotSupported", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No current record..
/// </summary>
internal static string NoCurrentRecord {
get {
return ResourceManager.GetString("NoCurrentRecord", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The CSV does not have headers (CsvReader.HasHeaders property is false)..
/// </summary>
internal static string NoHeaders {
get {
return ResourceManager.GetString("NoHeaders", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The number of fields in the record is greater than the available space from index to the end of the destination array..
/// </summary>
internal static string NotEnoughSpaceInArray {
get {
return ResourceManager.GetString("NotEnoughSpaceInArray", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &apos;{0}&apos; is not a valid ParseErrorAction while inside a ParseError event..
/// </summary>
internal static string ParseErrorActionInvalidInsideParseErrorEvent {
get {
return ResourceManager.GetString("ParseErrorActionInvalidInsideParseErrorEvent", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to &apos;{0}&apos; is not a supported ParseErrorAction..
/// </summary>
internal static string ParseErrorActionNotSupported {
get {
return ResourceManager.GetString("ParseErrorActionNotSupported", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This operation is invalid when the reader is closed..
/// </summary>
internal static string ReaderClosed {
get {
return ResourceManager.GetString("ReaderClosed", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Record index must be 0 or more..
/// </summary>
internal static string RecordIndexLessThanZero {
get {
return ResourceManager.GetString("RecordIndexLessThanZero", resourceCulture);
}
}
}
}

View file

@ -0,0 +1,175 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="BufferSizeTooSmall" xml:space="preserve">
<value>Buffer size must be 1 or more.</value>
</data>
<data name="CannotMovePreviousRecordInForwardOnly" xml:space="preserve">
<value>Cannot move to a previous record in forward-only mode.</value>
</data>
<data name="CannotReadRecordAtIndex" xml:space="preserve">
<value>Cannot read record at index '{0}'.</value>
<comment>index:int</comment>
</data>
<data name="EnumerationFinishedOrNotStarted" xml:space="preserve">
<value>Enumeration has either not started or has already finished.</value>
</data>
<data name="EnumerationVersionCheckFailed" xml:space="preserve">
<value>Collection was modified; enumeration operation may not execute.</value>
</data>
<data name="FieldHeaderNotFound" xml:space="preserve">
<value>'{0}' field header not found.</value>
<comment>header:string</comment>
</data>
<data name="FieldIndexOutOfRange" xml:space="preserve">
<value>Field index must be included in [0, FieldCount[. Specified field index was : '{0}'.</value>
<comment>index:int</comment>
</data>
<data name="MalformedCsvException" xml:space="preserve">
<value>The CSV appears to be corrupt near record '{0}' field '{1} at position '{2}'. Current raw data : '{3}'.</value>
<comment>currentRecordIndex:int;currentFieldIndex:int;currentPosition:int;rawData:string</comment>
</data>
<data name="MissingFieldActionNotSupported" xml:space="preserve">
<value>'{0}' is not a supported missing field action.</value>
<comment>missingFieldAction:LumenWorks.Framework.IO.Csv.MissingFieldAction</comment>
</data>
<data name="NoCurrentRecord" xml:space="preserve">
<value>No current record.</value>
</data>
<data name="NoHeaders" xml:space="preserve">
<value>The CSV does not have headers (CsvReader.HasHeaders property is false).</value>
</data>
<data name="NotEnoughSpaceInArray" xml:space="preserve">
<value>The number of fields in the record is greater than the available space from index to the end of the destination array.</value>
</data>
<data name="ParseErrorActionInvalidInsideParseErrorEvent" xml:space="preserve">
<value>'{0}' is not a valid ParseErrorAction while inside a ParseError event.</value>
<comment>parseErrorAction:LumenWorks.Framework.IO.Csv.ParseErrorAction</comment>
</data>
<data name="ParseErrorActionNotSupported" xml:space="preserve">
<value>'{0}' is not a supported ParseErrorAction.</value>
<comment>parseErrorAction:LumenWorks.Framework.IO.Csv.ParseErrorAction</comment>
</data>
<data name="ReaderClosed" xml:space="preserve">
<value>This operation is invalid when the reader is closed.</value>
</data>
<data name="RecordIndexLessThanZero" xml:space="preserve">
<value>Record index must be 0 or more.</value>
</data>
</root>

View file

@ -0,0 +1,13 @@
using System;
namespace LumenWorks.Framework.IO.Csv
{
[Flags]
public enum ValueTrimmingOptions
{
None = 0,
UnquotedOnly = 1,
QuotedOnly = 2,
All = UnquotedOnly | QuotedOnly
}
}

View file

@ -1,55 +0,0 @@
-----------------------
FileHelpers
-----------------------
http://www.filehelpers.com - SF Home: http://sourceforge.net/projects/filehelpers
The FileHelpers are an easy to use library to import/export data from fixed length or delimited files.
If you want to start using the library go directly to the Quick Start Guide in the CHM.
----------------------------------------
Who needs the File Helpers Library ?
----------------------------------------
In almost every project there is a need to read/write data from/to a file of a specified format.
For example for log parsing, data warehouse and OLAP applications,
communication between systems, file format transformations
(for example from a fixed length to a CSV file).
This library aims to provide an easy and reliable way to accomplish this task.
-----------
History
-----------
Check The docs for the History (is hard to mantain two copies =)
-----------
Licence
-----------
FileHelpers Library is @ Copyright 2005-2006 to Marcos Meli but it's source code and the binaries are free for commercial and non commercial use.
---------------------
Contact and Ideas
---------------------
If you find that there is a feature that I must include, or you have a new idea
(for the API, Source Code or Examples), only let me know, sending an e-mail
to marcos@filehelpers.com or entering the FileHelpers Forums at
http://www.filehelpers.com/forums/
----------------------------
Full Sources and Updates
----------------------------
If you want to help in the develpment of the library please go to
http://sourceforge.net/project/showfiles.php?group_id=152382&package_id=169468
and download the AllInOne DevPack with the binaries of NUnit, NAnt and NDoc.

View file

@ -1,203 +0,0 @@
using System;
using System.ComponentModel;
using System.Text;
using System.Diagnostics;
namespace FileHelpers
{
/// <summary>Base class for the two engines of the library: <see cref="FileHelperEngine"/> and <see cref="FileHelperAsyncEngine"/></summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public abstract class EngineBase
{
#if NET_2_0
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
#endif
internal RecordInfo mRecordInfo;
#region " Constructor "
internal EngineBase(Type recordType):this(recordType, Encoding.Default)
{}
internal EngineBase(Type recordType, Encoding encoding)
{
if (recordType == null)
throw new BadUsageException("The record type can't be null");
if (recordType.IsValueType)
throw new BadUsageException("The record type must be a class not a struct.");
mRecordType = recordType;
mRecordInfo = new RecordInfo(recordType);
mEncoding = encoding;
}
internal EngineBase(RecordInfo ri)
{
mRecordType = ri.mRecordType;
mRecordInfo = ri;
}
#endregion
#region " LineNumber "
#if NET_2_0
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
#endif
internal int mLineNumber;
#if NET_2_0
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
#endif
internal int mTotalRecords;
/// <include file='FileHelperEngine.docs.xml' path='doc/LineNum/*'/>
public int LineNumber
{
get { return mLineNumber; }
}
#endregion
#region " TotalRecords "
/// <include file='FileHelperEngine.docs.xml' path='doc/TotalRecords/*'/>
public int TotalRecords
{
get { return mTotalRecords; }
}
#endregion
#region " RecordType "
#if NET_2_0
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
#endif
private Type mRecordType;
/// <include file='FileHelperEngine.docs.xml' path='doc/RecordType/*'/>
public Type RecordType
{
get { return mRecordType; }
}
#endregion
#region " HeaderText "
#if NET_2_0
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
#endif
internal string mHeaderText = String.Empty;
/// <summary>The read header in the last read operation. If any.</summary>
public string HeaderText
{
get { return mHeaderText; }
set { mHeaderText = value; }
}
#endregion
#region " FooterText"
#if NET_2_0
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
#endif
internal string mFooterText = String.Empty;
/// <summary>The read footer in the last read operation. If any.</summary>
public string FooterText
{
get { return mFooterText; }
set { mFooterText = value; }
}
#endregion
#region " Encoding "
#if NET_2_0
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
#endif
internal Encoding mEncoding = Encoding.Default;
/// <summary>The encoding to Read and Write the streams.</summary>
/// <remarks>Default is the system's current ANSI code page.</remarks>
/// <value>Default is the system's current ANSI code page.</value>
public Encoding Encoding
{
get { return mEncoding; }
set { mEncoding = value; }
}
#endregion
#region " ErrorManager"
#if NET_2_0
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
#endif
/// <summary>This is a common class that manage the errors of the library.</summary>
protected ErrorManager mErrorManager = new ErrorManager();
/// <summary>This is a common class that manage the errors of the library.</summary>
/// <remarks>You can, for example, get the errors, their number, Save them to a file, etc.</remarks>
public ErrorManager ErrorManager
{
get { return mErrorManager; }
}
#endregion
#region " ResetFields "
internal void ResetFields()
{
mLineNumber = 0;
mErrorManager.ClearErrors();
mTotalRecords = 0;
}
#endregion
#if ! MINI
#if NET_2_0
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
#endif
/// <summary></summary>
protected ProgressMode mProgressMode = ProgressMode.DontNotify;
#if NET_2_0
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
#endif
/// <summary></summary>
protected ProgressChangeHandler mNotifyHandler = null;
/// <summary>Set the handler to the engine used to notify progress into the operations.</summary>
/// <param name="handler">The <see cref="ProgressChangeHandler"/></param>
public void SetProgressHandler(ProgressChangeHandler handler)
{
SetProgressHandler(handler, ProgressMode.NotifyRecords);
}
/// <summary>Set the handler to the engine used to notify progress into the operations.</summary>
/// <param name="handler">Your <see cref="ProgressChangeHandler"/> method.</param>
/// <param name="mode">The <see cref="ProgressMode"/> to use.</param>
public void SetProgressHandler(ProgressChangeHandler handler, ProgressMode mode)
{
mNotifyHandler = handler;
if (mode == ProgressMode.NotifyBytes)
throw new NotImplementedException("Not implemented yet. Planed for version 1.5.0");
mProgressMode = mode;
}
#endif
}
}

View file

@ -1,897 +0,0 @@
#undef GENERICS
//#define GENERICS
//#if NET_2_0
#region " © Copyright 2005-07 to Marcos Meli - http://www.marcosmeli.com.ar"
// Errors, suggestions, contributions, send a mail to: marcos@filehelpers.com.
#endregion
using System;
using System.Data;
using System.Diagnostics;
using System.Collections;
using System.ComponentModel;
using System.IO;
using System.Reflection;
using System.Text;
#if GENERICS
using System.Collections.Generic;
#endif
#if ! MINI
//using System.Data;
#endif
namespace FileHelpers
{
/// <include file='FileHelperEngine.docs.xml' path='doc/FileHelperEngine/*'/>
/// <include file='Examples.xml' path='doc/examples/FileHelperEngine/*'/>
#if NET_2_0
[DebuggerDisplay("FileHelperEngine for type: {RecordType.Name}. ErrorMode: {ErrorManager.ErrorMode.ToString()}. Encoding: {Encoding.EncodingName}")]
#endif
#if ! GENERICS
public class FileHelperEngine : EngineBase
#else
/// <typeparam name="T">The record type.</typeparam>
public class FileHelperEngine<T>: EngineBase
#endif
{
#region " Constructor "
/// <include file='FileHelperEngine.docs.xml' path='doc/FileHelperEngineCtr/*'/>
#if ! GENERICS
public FileHelperEngine(Type recordType)
: this(recordType, Encoding.Default)
#else
public FileHelperEngine()
: this(Encoding.Default)
#endif
{}
/// <include file='FileHelperEngine.docs.xml' path='doc/FileHelperEngineCtr/*'/>
/// <param name="encoding">The Encoding used by the engine.</param>
#if ! GENERICS
public FileHelperEngine(Type recordType, Encoding encoding)
: base(recordType, encoding)
#else
public FileHelperEngine(Encoding encoding)
: base(typeof(T), encoding)
#endif
{
CreateRecordOptions();
}
private void CreateRecordOptions()
{
if (mRecordInfo.IsDelimited)
mOptions = new DelimitedRecordOptions(mRecordInfo);
else
mOptions = new FixedRecordOptions(mRecordInfo);
}
internal FileHelperEngine(RecordInfo ri)
: base(ri)
{
CreateRecordOptions();
}
#endregion
#region " ReadFile "
/// <include file='FileHelperEngine.docs.xml' path='doc/ReadFile/*'/>
#if ! GENERICS
public object[] ReadFile(string fileName)
#else
public T[] ReadFile(string fileName)
#endif
{
return ReadFile(fileName, int.MaxValue);
}
/// <include file='FileHelperEngine.docs.xml' path='doc/ReadFile/*'/>
/// <param name="maxRecords">The max number of records to read. Int32.MaxValue or -1 to read all records.</param>
#if ! GENERICS
public object[] ReadFile(string fileName, int maxRecords)
#else
public T[] ReadFile(string fileName, int maxRecords)
#endif
{
using (StreamReader fs = new StreamReader(fileName, mEncoding, true))
{
#if ! GENERICS
object[] tempRes;
#else
T[] tempRes;
#endif
tempRes = ReadStream(fs, maxRecords);
fs.Close();
return tempRes;
}
}
#endregion
#region " ReadStream "
/// <include file='FileHelperEngine.docs.xml' path='doc/ReadStream/*'/>
[EditorBrowsable(EditorBrowsableState.Advanced)]
#if ! GENERICS
public object[] ReadStream(TextReader reader)
#else
public T[] ReadStream(TextReader reader)
#endif
{
return ReadStream(reader, int.MaxValue);
}
/// <include file='FileHelperEngine.docs.xml' path='doc/ReadStream/*'/>
/// <param name="maxRecords">The max number of records to read. Int32.MaxValue or -1 to read all records.</param>
[EditorBrowsable(EditorBrowsableState.Advanced)]
#if ! GENERICS
public object[] ReadStream(TextReader reader, int maxRecords)
#else
public T[] ReadStream(TextReader reader, int maxRecords)
#endif
{
#if ! MINI
return ReadStream(reader, maxRecords, null);
}
#if ! GENERICS
private object[] ReadStream(TextReader reader, int maxRecords, DataTable dt)
#else
private T[] ReadStream(TextReader reader, int maxRecords, DataTable dt)
#endif
{
#endif
if (reader == null)
throw new ArgumentNullException("reader", "The reader of the Stream can´t be null");
ResetFields();
mHeaderText = String.Empty;
mFooterText = String.Empty;
ArrayList resArray = new ArrayList();
int currentRecord = 0;
ForwardReader freader = new ForwardReader(reader, mRecordInfo.mIgnoreLast);
freader.DiscardForward = true;
string currentLine, completeLine;
mLineNumber = 1;
completeLine = freader.ReadNextLine();
currentLine = completeLine;
#if !MINI
ProgressHelper.Notify(mNotifyHandler, mProgressMode, 0, -1);
#endif
if (mRecordInfo.mIgnoreFirst > 0)
{
for (int i = 0; i < mRecordInfo.mIgnoreFirst && currentLine != null; i++)
{
mHeaderText += currentLine + StringHelper.NewLine;
currentLine = freader.ReadNextLine();
mLineNumber++;
}
}
bool byPass = false;
if (maxRecords < 0)
maxRecords = int.MaxValue;
LineInfo line = new LineInfo(currentLine);
line.mReader = freader;
while (currentLine != null && currentRecord < maxRecords)
{
try
{
mTotalRecords++;
currentRecord++;
line.ReLoad(currentLine);
bool skip = false;
#if !MINI
ProgressHelper.Notify(mNotifyHandler, mProgressMode, currentRecord, -1);
skip = OnBeforeReadRecord(currentLine);
#endif
if (skip == false)
{
object record = mRecordInfo.StringToRecord(line);
#if !MINI
#if ! GENERICS
skip = OnAfterReadRecord(currentLine, record);
#else
skip = OnAfterReadRecord(currentLine, (T) record);
#endif
#endif
if (skip == false && record != null)
{
#if MINI
resArray.Add(record);
#else
if (dt == null)
resArray.Add(record);
else
dt.Rows.Add(mRecordInfo.RecordToValues(record));
#endif
}
}
}
catch (Exception ex)
{
switch (mErrorManager.ErrorMode)
{
case ErrorMode.ThrowException:
byPass = true;
throw;
case ErrorMode.IgnoreAndContinue:
break;
case ErrorMode.SaveAndContinue:
ErrorInfo err = new ErrorInfo();
err.mLineNumber = freader.LineNumber;
err.mExceptionInfo = ex;
// err.mColumnNumber = mColumnNum;
err.mRecordString = completeLine;
mErrorManager.AddError(err);
break;
}
}
finally
{
if (byPass == false)
{
currentLine = freader.ReadNextLine();
completeLine = currentLine;
mLineNumber++;
}
}
}
if (mRecordInfo.mIgnoreLast > 0)
{
mFooterText = freader.RemainingText;
}
#if ! GENERICS
return (object[])
#else
return (T[])
#endif
resArray.ToArray(RecordType);
}
#endregion
#region " ReadString "
/// <include file='FileHelperEngine.docs.xml' path='doc/ReadString/*'/>
#if ! GENERICS
public object[] ReadString(string source)
#else
public T[] ReadString(string source)
#endif
{
return ReadString(source, int.MaxValue);
}
/// <include file='FileHelperEngine.docs.xml' path='doc/ReadString/*'/>
/// <param name="maxRecords">The max number of records to read. Int32.MaxValue or -1 to read all records.</param>
#if ! GENERICS
public object[] ReadString(string source, int maxRecords)
#else
public T[] ReadString(string source, int maxRecords)
#endif
{
if (source == null)
source = string.Empty;
using (StringReader reader = new StringReader(source))
{
#if ! GENERICS
object[] res;
#else
T[] res;
#endif
res= ReadStream(reader, maxRecords);
reader.Close();
return res;
}
}
#endregion
#region " WriteFile "
/// <include file='FileHelperEngine.docs.xml' path='doc/WriteFile/*'/>
#if ! GENERICS
public void WriteFile(string fileName, IEnumerable records)
#else
public void WriteFile(string fileName, IEnumerable<T> records)
#endif
{
WriteFile(fileName, records, -1);
}
/// <include file='FileHelperEngine.docs.xml' path='doc/WriteFile2/*'/>
#if ! GENERICS
public void WriteFile(string fileName, IEnumerable records, int maxRecords)
#else
public void WriteFile(string fileName, IEnumerable<T> records, int maxRecords)
#endif
{
using (StreamWriter fs = new StreamWriter(fileName, false, mEncoding))
{
WriteStream(fs, records, maxRecords);
fs.Close();
}
}
#endregion
#region " WriteStream "
/// <include file='FileHelperEngine.docs.xml' path='doc/WriteStream/*'/>
[EditorBrowsable(EditorBrowsableState.Advanced)]
#if ! GENERICS
public void WriteStream(TextWriter writer, IEnumerable records)
#else
public void WriteStream(TextWriter writer, IEnumerable<T> records)
#endif
{
WriteStream(writer, records, -1);
}
/// <include file='FileHelperEngine.docs.xml' path='doc/WriteStream2/*'/>
[EditorBrowsable(EditorBrowsableState.Advanced)]
#if ! GENERICS
public void WriteStream(TextWriter writer, IEnumerable records, int maxRecords)
#else
public void WriteStream(TextWriter writer, IEnumerable<T> records, int maxRecords)
#endif
{
if (writer == null)
throw new ArgumentNullException("writer", "The writer of the Stream can be null");
if (records == null)
throw new ArgumentNullException("records", "The records can be null. Try with an empty array.");
ResetFields();
if (mHeaderText != null && mHeaderText.Length != 0)
if (mHeaderText.EndsWith(StringHelper.NewLine))
writer.Write(mHeaderText);
else
writer.WriteLine(mHeaderText);
string currentLine = null;
//ConstructorInfo constr = mType.GetConstructor(new Type[] {});
int max = maxRecords;
if (records is IList)
max = Math.Min(max < 0 ? int.MaxValue : max, ((IList)records).Count);
#if !MINI
ProgressHelper.Notify(mNotifyHandler, mProgressMode, 0, max);
#endif
int recIndex = 0;
bool first = true;
#if ! GENERICS
foreach(object rec in records)
#else
foreach (T rec in records)
#endif
{
if (recIndex == maxRecords)
break;
mLineNumber++;
try
{
if (rec == null)
throw new BadUsageException("The record at index " + recIndex.ToString() + " is null.");
if (first)
{
first = false;
if (mRecordInfo.mRecordType.IsInstanceOfType(rec) == false)
throw new BadUsageException("This engine works with record of type " + mRecordInfo.mRecordType.Name + " and you use records of type " + rec.GetType().Name );
}
bool skip = false;
#if !MINI
ProgressHelper.Notify(mNotifyHandler, mProgressMode, recIndex+1, max);
skip = OnBeforeWriteRecord(rec);
#endif
if (skip == false)
{
currentLine = mRecordInfo.RecordToString(rec);
#if !MINI
currentLine = OnAfterWriteRecord(currentLine, rec);
#endif
writer.WriteLine(currentLine);
}
}
catch (Exception ex)
{
switch (mErrorManager.ErrorMode)
{
case ErrorMode.ThrowException:
throw;
case ErrorMode.IgnoreAndContinue:
break;
case ErrorMode.SaveAndContinue:
ErrorInfo err = new ErrorInfo();
err.mLineNumber = mLineNumber;
err.mExceptionInfo = ex;
// err.mColumnNumber = mColumnNum;
err.mRecordString = currentLine;
mErrorManager.AddError(err);
break;
}
}
recIndex++;
}
mTotalRecords = recIndex;
if (mFooterText != null && mFooterText != string.Empty)
if (mFooterText.EndsWith(StringHelper.NewLine))
writer.Write(mFooterText);
else
writer.WriteLine(mFooterText);
}
#endregion
#region " WriteString "
/// <include file='FileHelperEngine.docs.xml' path='doc/WriteString/*'/>
#if ! GENERICS
public string WriteString(IEnumerable records)
#else
public string WriteString(IEnumerable<T> records)
#endif
{
return WriteString(records, -1);
}
/// <include file='FileHelperEngine.docs.xml' path='doc/WriteString2/*'/>
#if ! GENERICS
public string WriteString(IEnumerable records, int maxRecords)
#else
public string WriteString(IEnumerable<T> records, int maxRecords)
#endif
{
StringBuilder sb = new StringBuilder();
StringWriter writer = new StringWriter(sb);
WriteStream(writer, records, maxRecords);
string res = writer.ToString();
writer.Close();
return res;
}
#endregion
#region " AppendToFile "
/// <include file='FileHelperEngine.docs.xml' path='doc/AppendToFile1/*'/>
#if ! GENERICS
public void AppendToFile(string fileName, object record)
{
AppendToFile(fileName, new object[] {record});
}
#else
public void AppendToFile(string fileName, T record)
{
AppendToFile(fileName, new T[] {record});
}
#endif
/// <include file='FileHelperEngine.docs.xml' path='doc/AppendToFile2/*'/>
#if ! GENERICS
public void AppendToFile(string fileName, IEnumerable records)
#else
public void AppendToFile(string fileName, IEnumerable<T> records)
#endif
{
using(TextWriter writer = StreamHelper.CreateFileAppender(fileName, mEncoding, true, false))
{
mHeaderText = String.Empty;
mFooterText = String.Empty;
WriteStream(writer, records);
writer.Close();
}
}
#endregion
#region " DataTable Ops "
#if ! MINI
/// <summary>
/// Read the records of the file and fill a DataTable with them
/// </summary>
/// <param name="fileName">The file name.</param>
/// <returns>The DataTable with the read records.</returns>
public DataTable ReadFileAsDT(string fileName)
{
return ReadFileAsDT(fileName, -1);
}
/// <summary>
/// Read the records of the file and fill a DataTable with them
/// </summary>
/// <param name="fileName">The file name.</param>
/// <param name="maxRecords">The max number of records to read. Int32.MaxValue or -1 to read all records.</param>
/// <returns>The DataTable with the read records.</returns>
public DataTable ReadFileAsDT(string fileName, int maxRecords)
{
using (StreamReader fs = new StreamReader(fileName, mEncoding, true))
{
DataTable res;
res = ReadStreamAsDT(fs, maxRecords);
fs.Close();
return res;
}
}
/// <summary>
/// Read the records of a string and fill a DataTable with them.
/// </summary>
/// <param name="source">The source string with the records.</param>
/// <returns>The DataTable with the read records.</returns>
public DataTable ReadStringAsDT(string source)
{
return ReadStringAsDT(source, -1);
}
/// <summary>
/// Read the records of a string and fill a DataTable with them.
/// </summary>
/// <param name="source">The source string with the records.</param>
/// <param name="maxRecords">The max number of records to read. Int32.MaxValue or -1 to read all records.</param>
/// <returns>The DataTable with the read records.</returns>
public DataTable ReadStringAsDT(string source, int maxRecords)
{
if (source == null)
source = string.Empty;
using (StringReader reader = new StringReader(source))
{
DataTable res;
res = ReadStreamAsDT(reader, maxRecords);
reader.Close();
return res;
}
}
/// <summary>
/// Read the records of the stream and fill a DataTable with them
/// </summary>
/// <param name="reader">The stream with the source records.</param>
/// <returns>The DataTable with the read records.</returns>
public DataTable ReadStreamAsDT(TextReader reader)
{
return ReadStreamAsDT(reader, -1);
}
/// <summary>
/// Read the records of the stream and fill a DataTable with them
/// </summary>
/// <param name="reader">The stream with the source records.</param>
/// <param name="maxRecords">The max number of records to read. Int32.MaxValue or -1 to read all records.</param>
/// <returns>The DataTable with the read records.</returns>
public DataTable ReadStreamAsDT(TextReader reader, int maxRecords)
{
DataTable dt = mRecordInfo.CreateEmptyDataTable();
dt.BeginLoadData();
ReadStream(reader, maxRecords, dt);
dt.EndLoadData();
return dt;
}
#endif
#endregion
#region " Event Handling "
#if ! MINI
#if NET_1_1
/// <summary>Called in read operations just before the record string is translated to a record.</summary>
public event BeforeReadRecordHandler BeforeReadRecord;
/// <summary>Called in read operations just after the record was created from a record string.</summary>
public event AfterReadRecordHandler AfterReadRecord;
/// <summary>Called in write operations just before the record is converted to a string to write it.</summary>
public event BeforeWriteRecordHandler BeforeWriteRecord;
/// <summary>Called in write operations just after the record was converted to a string.</summary>
public event AfterWriteRecordHandler AfterWriteRecord;
private bool OnBeforeReadRecord(string line)
{
if (BeforeReadRecord != null)
{
BeforeReadRecordEventArgs e = null;
e = new BeforeReadRecordEventArgs(line, mLineNumber);
BeforeReadRecord(this, e);
return e.SkipThisRecord;
}
return false;
}
private bool OnAfterReadRecord(string line, object record)
{
if (mRecordInfo.mNotifyRead)
((INotifyRead)record).AfterRead(this, line);
if (AfterReadRecord != null)
{
AfterReadRecordEventArgs e = null;
e = new AfterReadRecordEventArgs(line, record, mLineNumber);
AfterReadRecord(this, e);
return e.SkipThisRecord;
}
return false;
}
private bool OnBeforeWriteRecord(object record)
{
if (mRecordInfo.mNotifyWrite)
((INotifyWrite)record).BeforeWrite(this);
if (BeforeWriteRecord != null)
{
BeforeWriteRecordEventArgs e = null;
e = new BeforeWriteRecordEventArgs(record, mLineNumber);
BeforeWriteRecord(this, e);
return e.SkipThisRecord;
}
return false;
}
private string OnAfterWriteRecord(string line, object record)
{
if (AfterWriteRecord != null)
{
AfterWriteRecordEventArgs e = null;
e = new AfterWriteRecordEventArgs(record, mLineNumber, line);
AfterWriteRecord(this, e);
return e.RecordLine;
}
return line;
}
#else
#if ! GENERICS
/// <summary>Called in read operations just before the record string is translated to a record.</summary>
public event BeforeReadRecordHandler BeforeReadRecord;
/// <summary>Called in read operations just after the record was created from a record string.</summary>
public event AfterReadRecordHandler AfterReadRecord;
/// <summary>Called in write operations just before the record is converted to a string to write it.</summary>
public event BeforeWriteRecordHandler BeforeWriteRecord;
/// <summary>Called in write operations just after the record was converted to a string.</summary>
public event AfterWriteRecordHandler AfterWriteRecord;
private bool OnBeforeReadRecord(string line)
{
if (BeforeReadRecord != null)
{
BeforeReadRecordEventArgs e = null;
e = new BeforeReadRecordEventArgs(line, LineNumber);
BeforeReadRecord(this, e);
return e.SkipThisRecord;
}
return false;
}
private bool OnAfterReadRecord(string line, object record)
{
if (mRecordInfo.mNotifyRead)
((INotifyRead)record).AfterRead(this, line);
if (AfterReadRecord != null)
{
AfterReadRecordEventArgs e = null;
e = new AfterReadRecordEventArgs(line, record, LineNumber);
AfterReadRecord(this, e);
return e.SkipThisRecord;
}
return false;
}
private bool OnBeforeWriteRecord(object record)
{
if (mRecordInfo.mNotifyWrite)
((INotifyWrite)record).BeforeWrite(this);
if (BeforeWriteRecord != null)
{
BeforeWriteRecordEventArgs e = null;
e = new BeforeWriteRecordEventArgs(record, LineNumber);
BeforeWriteRecord(this, e);
return e.SkipThisRecord;
}
return false;
}
private string OnAfterWriteRecord(string line, object record)
{
if (AfterWriteRecord != null)
{
AfterWriteRecordEventArgs e = null;
e = new AfterWriteRecordEventArgs(record, LineNumber, line);
AfterWriteRecord(this, e);
return e.RecordLine;
}
return line;
}
#else
/// <summary>Called in read operations just before the record string is translated to a record.</summary>
public event BeforeReadRecordHandler<T> BeforeReadRecord;
/// <summary>Called in read operations just after the record was created from a record string.</summary>
public event AfterReadRecordHandler<T> AfterReadRecord;
/// <summary>Called in write operations just before the record is converted to a string to write it.</summary>
public event BeforeWriteRecordHandler<T> BeforeWriteRecord;
/// <summary>Called in write operations just after the record was converted to a string.</summary>
public event AfterWriteRecordHandler<T> AfterWriteRecord;
private bool OnBeforeReadRecord(string line)
{
if (BeforeReadRecord != null)
{
BeforeReadRecordEventArgs<T> e = null;
e = new BeforeReadRecordEventArgs<T>(line, LineNumber);
BeforeReadRecord(this, e);
return e.SkipThisRecord;
}
return false;
}
private bool OnAfterReadRecord(string line, T record)
{
if (mRecordInfo.mNotifyRead)
((INotifyRead)record).AfterRead(this, line);
if (AfterReadRecord != null)
{
AfterReadRecordEventArgs<T> e = null;
e = new AfterReadRecordEventArgs<T>(line, record, LineNumber);
AfterReadRecord(this, e);
return e.SkipThisRecord;
}
return false;
}
private bool OnBeforeWriteRecord(T record)
{
if (mRecordInfo.mNotifyWrite)
((INotifyWrite)record).BeforeWrite(this);
if (BeforeWriteRecord != null)
{
BeforeWriteRecordEventArgs<T> e = null;
e = new BeforeWriteRecordEventArgs<T>(record, LineNumber);
BeforeWriteRecord(this, e);
return e.SkipThisRecord;
}
return false;
}
private string OnAfterWriteRecord(string line, T record)
{
if (AfterWriteRecord != null)
{
AfterWriteRecordEventArgs<T> e = null;
e = new AfterWriteRecordEventArgs<T>(record, LineNumber, line);
AfterWriteRecord(this, e);
return e.RecordLine;
}
return line;
}
#endif
#endif
#endif
#endregion
#if NET_2_0
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
#endif
internal RecordOptions mOptions;
/// <summary>
/// Allows to change some record layout options at runtime
/// </summary>
public RecordOptions Options
{
get { return mOptions; }
set { mOptions = value; }
}
}
}
//#endif

View file

@ -1,21 +0,0 @@
#region " © Copyright 2005-07 to Marcos Meli - http://www.marcosmeli.com.ar"
// Errors, suggestions, contributions, send a mail to: marcos@filehelpers.com.
#endregion
namespace FileHelpers
{
/// <summary>Indicates the align of the field when the <see cref="T:FileHelpers.FileHelperEngine"/> <b>writes</b> the record.</summary>
public enum AlignMode
{
/// <summary>Aligns the field to the left.</summary>
Left,
/// <summary>Aligns the field to the center.</summary>
Center,
/// <summary>Aligns the field to the right.</summary>
Right
}
}

View file

@ -1,81 +0,0 @@
#region " © Copyright 2005-07 to Marcos Meli - http://www.marcosmeli.com.ar"
// Errors, suggestions, contributions, send a mail to: marcos@filehelpers.com.
#endregion
namespace FileHelpers
{
/// <summary>Indicates the convertion used in the <see cref="T:FileHelpers.FieldConverterAttribute"/>.</summary>
public enum ConverterKind
{
/// <summary>Null Converter.</summary>
None = 0,
/// <summary>
/// <para>Convert from/to <b>Date</b> values.</para>
/// <para>Params: arg1 is the <b>string</b> with the date format.</para>
/// </summary>
Date,
/// <summary>Convert from/to <b>Boolean</b> values.</summary>
Boolean,
/// <summary>
/// <para>Convert from/to <b>Byte</b> values.</para>
/// <para>Params: arg1 is the <b>decimal separator</b>, by default '.'</para>
/// </summary>
Byte,
/// <summary>
/// <para>Convert from/to <b>Int16 or short</b> values.</para>
/// <para>Params: arg1 is the <b>decimal separator</b>, by default '.'</para>
/// </summary>
Int16,
/// <summary>
/// <para>Convert from/to <b>Int32 or int</b> values.</para>
/// <para>Params: arg1 is the <b>decimal separator</b>, by default '.'</para>
/// </summary>
Int32,
/// <summary>
/// <para>Convert from/to <b>Int64 or long</b> values.</para>
/// <para>Params: arg1 is the <b>decimal separator</b>, by default '.'</para>
/// </summary>
Int64,
/// <summary>
/// <para>Convert from/to <b>Decimal</b> values.</para>
/// <para>Params: arg1 is the <b>decimal separator</b>, by default '.'</para>
/// </summary>
Decimal,
/// <summary>
/// <para>Convert from/to <b>Double</b> values.</para>
/// <para>Params: arg1 is the <b>decimal separator</b>, by default '.'</para>
/// </summary>
Double,
/// <summary>
/// <para>Convert from/to <b>Single</b> values.</para>
/// <para>Params: arg1 is the <b>decimal separator</b>, by default '.'</para>
/// </summary>
Single,
/// <summary>
/// <para>Convert from/to <b>Byte</b> values.</para>
/// <para>Params: arg1 is the <b>decimal separator</b>, by default '.'</para>
/// </summary>
SByte,
/// <summary>
/// <para>Convert from/to <b>UInt16 or unsigned short</b> values.</para>
/// <para>Params: arg1 is the <b>decimal separator</b>, by default '.'</para>
/// </summary>
UInt16,
/// <summary>
/// <para>Convert from/to <b>UInt32 or unsigned int</b> values.</para>
/// <para>Params: arg1 is the <b>decimal separator</b>, by default '.'</para>
/// </summary>
UInt32,
/// <summary>
/// <para>Convert from/to <b>UInt64 or unsigned long</b> values.</para>
/// <para>Params: arg1 is the <b>decimal separator</b>, by default '.'</para>
/// </summary>
UInt64
}
}

View file

@ -1,21 +0,0 @@
#region " © Copyright 2005-07 to Marcos Meli - http://www.marcosmeli.com.ar"
// Errors, suggestions, contributions, send a mail to: marcos@filehelpers.com.
#endregion
namespace FileHelpers
{
/// <summary>Indicates the behavior when the <see cref="FileHelperEngine"/> class found an error.</summary>
public enum ErrorMode
{
/// <summary>Default value, this simple Rethrow the original exception.</summary>
ThrowException = 0,
/// <summary>Add an <see cref="ErrorInfo"/> to the array of <see cref="ErrorManager.Errors"/>.</summary>
SaveAndContinue,
/// <summary>Simply ignores the exception an continue.</summary>
IgnoreAndContinue
}
}

View file

@ -1,23 +0,0 @@
#region " © Copyright 2005-07 to Marcos Meli - http://www.marcosmeli.com.ar"
// Errors, suggestions, contributions, send a mail to: marcos@filehelpers.com.
#endregion
namespace FileHelpers
{
/// <summary>Indicates the behavior when variable length records are found in a [<see cref="FixedLengthRecordAttribute"/>]. (Note: nothing in common with [FieldOptional])</summary>
public enum FixedMode
{
/// <summary>The records must have the length equals to the sum of each field length.</summary>
ExactLength = 0,
/// <summary>The records can contain less chars in the last field.</summary>
AllowMoreChars,
/// <summary>The records can contain more chars in the last field.</summary>
AllowLessChars,
/// <summary>The records can contain more or less chars in the last field.</summary>
AllowVariableLength
}
}

View file

@ -1,23 +0,0 @@
using System;
#region " © Copyright 2005-07 to Marcos Meli - http://www.marcosmeli.com.ar"
// Errors, suggestions, contributions, send a mail to: marcos@filehelpers.com.
#endregion
namespace FileHelpers
{
/// <summary>Indicates the behavior of multiline fields.</summary>
public enum MultilineMode
{
/// <summary>The engine can handle multiline values for read or write.</summary>
AllowForBoth = 0,
/// <summary>The engine can handle multiline values only for read.</summary>
AllowForRead,
/// <summary>The engine can handle multiline values only for write.</summary>
AllowForWrite,
/// <summary>The engine don´t allow multiline values for this field.</summary>
NotAllow
}
}

View file

@ -1,16 +0,0 @@
namespace FileHelpers
{
/// <summary>Indicate the method used to calculate the current progress</summary>
public enum ProgressMode
{
/// <summary>Notify the percent completed.</summary>
NotifyPercent,
/// <summary>Notify the Record completed.</summary>
NotifyRecords,
/// <summary>Notify the bytes readed.</summary>
NotifyBytes,
/// <summary>Dont call to the progress handler.</summary>
DontNotify = 0
}
}

View file

@ -1,23 +0,0 @@
using System;
#region " © Copyright 2005-07 to Marcos Meli - http://www.marcosmeli.com.ar"
// Errors, suggestions, contributions, send a mail to: marcos@filehelpers.com.
#endregion
namespace FileHelpers
{
/// <summary>Indicates the behavior of quoted fields.</summary>
public enum QuoteMode
{
/// <summary>The engine always expects a quote when read and always adds the quotes when write.</summary>
AlwaysQuoted = 0,
/// <summary>The engine expects or not a quote when read and always adds the quotes when write.</summary>
OptionalForRead,
/// <summary>The engine always expects a quote when read and adds the quotes when write only if the field contains: quotes, new lines or the separator char.</summary>
OptionalForWrite,
/// <summary>The engine expects or not a quote when read and adds the quotes when write only if the field contains: quotes, new lines or the separator char.</summary>
OptionalForBoth
}
}

View file

@ -1,41 +0,0 @@
using System;
namespace FileHelpers
{
/// <summary>The condition used to include or exclude each record.</summary>
public enum RecordCondition
{
/// <summary>No Condition, Include it always.</summary>
None = 0,
/// <summary>Include the record if it contains the selector string.</summary>
IncludeIfContains,
/// <summary>Include the record if it begins with selector string.</summary>
IncludeIfBegins,
/// <summary>Include the record if it ends with selector string.</summary>
IncludeIfEnds,
/// <summary>Include the record if it begins and ends with selector string.</summary>
IncludeIfEnclosed,
#if ! MINI
/// <summary>Include the record if it matchs the regular expression passed as selector.</summary>
IncludeIfMatchRegex,
#endif
/// <summary>Exclude the record if it contains the selector string.</summary>
ExcludeIfContains,
/// <summary>Exclude the record if it begins with selector string.</summary>
ExcludeIfBegins,
/// <summary>Exclude the record if it ends with selector string.</summary>
ExcludeIfEnds,
/// <summary>Exclude the record if it begins and ends with selector string.</summary>
ExcludeIfEnclosed
#if ! MINI
,
/// <summary>Exclude the record if it matchs the regular expression passed as selector.</summary>
ExcludeIfMatchRegex
#endif
}
}

View file

@ -1,23 +0,0 @@
#region " © Copyright 2005-07 to Marcos Meli - http://www.marcosmeli.com.ar"
// Errors, suggestions, contributions, send a mail to: marcos@filehelpers.com.
#endregion
namespace FileHelpers
{
/// <summary>Indicates the triming behavior of the trailing characters.</summary>
public enum TrimMode
{
/// <summary>No triming is performed.</summary>
None,
/// <summary>The field is trimed in both sides.</summary>
Both,
/// <summary>The field is trimed in the left.</summary>
Left,
/// <summary>The field is trimed in the right.</summary>
Right
}
}

View file

@ -1,28 +0,0 @@
using System;
#region " © Copyright 2005-07 to Marcos Meli - http://www.marcosmeli.com.ar"
// Errors, suggestions, contributions, send a mail to: marcos@filehelpers.com.
#endregion
namespace FileHelpers
{
/// <summary>Indicates the wrong usage of the library.</summary>
public class BadUsageException : FileHelpersException
{
/// <summary>Creates an instance of an BadUsageException.</summary>
/// <param name="message">The exception Message</param>
protected internal BadUsageException(string message) : base(message)
{
}
// /// <summary>Creates an instance of an BadUsageException.</summary>
// /// <param name="message">The exception Message</param>
// /// <param name="innerEx">The inner exception.</param>
// protected internal BadUsageException(string message, Exception innerEx) : base(message, innerEx)
// {
// }
}
}

View file

@ -1,150 +0,0 @@
#region " © Copyright 2005-07 to Marcos Meli - http://www.marcosmeli.com.ar"
// Errors, suggestions, contributions, send a mail to: marcos@filehelpers.com.
#endregion
using System;
using System.Diagnostics;
namespace FileHelpers
{
/// <summary>
/// Indicates that a string value can't be converted to a dest type.
/// </summary>
public sealed class ConvertException : FileHelpersException
{
#if NET_2_0
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
#endif
internal string mFieldName = null;
#if NET_2_0
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
#endif
internal int mLineNumber = -1;
#if NET_2_0
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
#endif
internal int mColumnNumber = -1;
#if NET_2_0
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
#endif
private string mFieldStringValue = null;
#if NET_2_0
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
#endif
private string mMessageExtra = string.Empty;
#if NET_2_0
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
#endif
private Type mFieldType;
/// <summary>The destination type.</summary>
public Type FieldType
{
get { return mFieldType; }
}
/// <summary>The value that cant be converterd. (null for unknown)</summary>
public string FieldStringValue
{
get { return mFieldStringValue; }
}
/// <summary>Extra info about the error.</summary>
public string MessageExtra
{
get { return mMessageExtra; }
}
/// <summary>The name of the field related to the exception. (null for unknown)</summary>
public string FieldName
{
get { return mFieldName; }
}
/// <summary>The line where the error was found. (-1 is unknown)</summary>
public int LineNumber
{
get { return mLineNumber; }
}
/// <summary>The estimate column where the error was found. (-1 is unknown)</summary>
public int ColumnNumber
{
get { return mColumnNumber; }
}
/// <summary>
/// Create a new ConvertException object
/// </summary>
/// <param name="origValue">The value to convert.</param>
/// <param name="destType">The destination Type.</param>
public ConvertException(string origValue, Type destType)
: this(origValue, destType, string.Empty)
{
}
/// <summary>
/// Create a new ConvertException object
/// </summary>
/// <param name="origValue">The value to convert.</param>
/// <param name="destType">The destination Type.</param>
/// <param name="extraInfo">Aditional info of the error.</param>
public ConvertException(string origValue, Type destType, string extraInfo)
: this(origValue, destType, string.Empty, -1, -1, extraInfo)
{
}
/// <summary>
/// Create a new ConvertException object
/// </summary>
/// <param name="origValue">The value to convert.</param>
/// <param name="destType">The destination Type.</param>
/// <param name="extraInfo">Aditional info of the error.</param>
/// <param name="columnNumber">The estimated column number.</param>
/// <param name="lineNumber">The line where the error was found.</param>
/// <param name="fieldName">The name of the field with the error</param>
public ConvertException(string origValue, Type destType, string fieldName, int lineNumber, int columnNumber, string extraInfo)
: base(MessageBuilder(origValue, destType, fieldName, lineNumber, columnNumber, extraInfo))
{
mFieldStringValue = origValue;
mFieldType = destType;
mLineNumber = lineNumber;
mColumnNumber = columnNumber;
mFieldName = fieldName;
mMessageExtra = extraInfo;
}
private static string MessageBuilder(string origValue, Type destType, string fieldName, int lineNumber, int columnNumber, string extraInfo)
{
string res = string.Empty;
if (lineNumber >= 0)
res += "Line: " + lineNumber.ToString() + ". ";
if (columnNumber >= 0)
res += "Column: " + columnNumber.ToString() + ". ";
if (fieldName != null && fieldName != string.Empty)
res += "Field: " + fieldName + ". ";
if (origValue != null && destType != null)
res += "Error Converting '" + origValue + "' to type: '" + destType.Name + "'. ";
res += extraInfo;
return res;
}
internal static ConvertException ReThrowException(ConvertException ex, string fieldName, int line, int column)
{
return new ConvertException(ex.FieldStringValue, ex.mFieldType, fieldName, line, column, ex.mMessageExtra);
}
}
}

View file

@ -1,81 +0,0 @@
#region " © Copyright 2005-07 to Marcos Meli - http://www.marcosmeli.com.ar"
// Errors, suggestions, contributions, send a mail to: marcos@filehelpers.com.
#endregion
using System;
using System.Diagnostics;
namespace FileHelpers
{
/// <summary>Contains error information of the <see cref="FileHelperEngine"/> class.</summary>
[DelimitedRecord("|")]
[IgnoreFirst(2)]
#if NET_2_0
[DebuggerDisplay("Line: {LineNumber}. Error: {ExceptionInfo.Message}.")]
#endif
public sealed class ErrorInfo
{
internal ErrorInfo()
{
}
#if NET_2_0
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
#endif
internal int mLineNumber;
/// <summary>The line number of the error</summary>
public int LineNumber
{
get { return mLineNumber; }
}
#if NET_2_0
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
#endif
[FieldQuoted(QuoteMode.OptionalForBoth)]
internal string mRecordString = string.Empty;
/// <summary>The string of the record of the error.</summary>
public string RecordString
{
get { return mRecordString; }
}
#if NET_2_0
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
#endif
[FieldConverter(typeof(ExceptionConverter))]
[FieldQuoted(QuoteMode.OptionalForBoth)]
internal Exception mExceptionInfo;
/// <summary>The exception that indicates the error.</summary>
public Exception ExceptionInfo
{
get { return mExceptionInfo; }
}
internal class ExceptionConverter : ConverterBase
{
public override string FieldToString(object from)
{
if (from == null)
return String.Empty;
else
{
if (from is ConvertException)
return "In the field '" + ((ConvertException) from).FieldName + "': " + ((ConvertException) from).Message.Replace(StringHelper.NewLine, " -> ");
else
return ((Exception) from).Message.Replace(StringHelper.NewLine, " -> ");
}
}
public override object StringToField(string from)
{
return new Exception(from);
}
}
}
}

View file

@ -1,148 +0,0 @@
#region " © Copyright 2005-07 to Marcos Meli - http://www.marcosmeli.com.ar"
// Errors, suggestions, contributions, send a mail to: marcos@filehelpers.com.
#endregion
using System;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
namespace FileHelpers
{
/// <summary>This is the class that handles the errors of the engines process.</summary>
/// <remarks>All the engines and DataStorages contains a ErrorManager.</remarks>
#if NET_2_0
[DebuggerDisplay("{ErrorsDescription()}. ErrorMode: {ErrorMode.ToString()}")]
#endif
public sealed class ErrorManager
{
/// <summary>Initializes a new instance of the <see cref="ErrorManager"/> class.</summary>
public ErrorManager()
{
}
/// <summary>Initializes a new instance of the <see cref="ErrorManager"/> class. with the specified <see cref="ErrorMode"/>.</summary>
/// <param name="mode">Indicates the error behavior of the class.</param>
public ErrorManager(ErrorMode mode)
{
mErrorMode = mode;
}
#if NET_2_0
private string ErrorsDescription()
{
if (ErrorCount == 1)
return ErrorCount.ToString() + " Error";
else if (ErrorCount == 0)
return "No Errors";
else
return ErrorCount.ToString() + " Errors";
}
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
#endif
ArrayList mErrorsArray = new ArrayList();
/// <summary>Is an array of <see cref="ErrorInfo"/> that contains the errors of the last operation in this class.</summary>
#if NET_2_0
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
#endif
public ErrorInfo[] Errors
{
get { return (ErrorInfo[]) mErrorsArray.ToArray(typeof (ErrorInfo)); }
}
#if NET_2_0
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
#endif
private ErrorMode mErrorMode = ErrorMode.ThrowException;
/// <summary>Indicates the behavior of the <see cref="FileHelperEngine"/> when it found an error.</summary>
public ErrorMode ErrorMode
{
get { return mErrorMode; }
set { mErrorMode = value; }
}
/// <summary>Number of contained errors.</summary>
public int ErrorCount
{
get { return mErrorsArray.Count; }
}
/// <summary>Indicates if contains one or more errors.</summary>
public bool HasErrors
{
get { return mErrorsArray.Count > 0; }
}
/// <summary>Clears the error collection.</summary>
public void ClearErrors()
{
mErrorsArray.Clear();
}
/// <summary>Add the specified ErrorInfo to the contained collection.</summary>
/// <param name="error"></param>
internal void AddError(ErrorInfo error)
{
mErrorsArray.Add(error);
}
/// <summary>Add the specified ErrorInfo to the contained collection.</summary>
internal void AddErrors(ErrorManager errors)
{
mErrorsArray.AddRange(errors.mErrorsArray);
}
// public void ProcessError(Exception ex, string line)
// {
// }
/// <summary>Saves the contained errors to the specified file.</summary>
/// <param name="fileName">The file that contains the errors.</param>
public void SaveErrors(string fileName)
{
string header;
if (ErrorCount > 0)
header = "FileHelpers - Errors Saved ";
else
header = "FileHelpers - NO Errors Found ";
header += "at " + DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString();
header += StringHelper.NewLine + "LineNumber | LineString |ErrorDescription";
SaveErrors(fileName, header);
}
/// <summary>Saves the contained errors to the specified file.</summary>
/// <param name="fileName">The file that contains the errors.</param>
/// <param name="header">The header line of the errors file.</param>
public void SaveErrors(string fileName, string header)
{
FileHelperEngine engine = new FileHelperEngine(typeof (ErrorInfo));
if (header.IndexOf(StringHelper.NewLine) == header.LastIndexOf(StringHelper.NewLine))
header += StringHelper.NewLine;
engine.HeaderText = header;
engine.WriteFile(fileName, Errors);
}
/// <summary>Load errors from a file.</summary>
/// <param name="fileName">The file that contains the errors.</param>
public static ErrorInfo[] LoadErrors(string fileName)
{
FileHelperEngine engine = new FileHelperEngine(typeof (ErrorInfo));
return (ErrorInfo[]) engine.ReadFile(fileName);
}
}
}

View file

@ -1,29 +0,0 @@
#region " © Copyright 2005-07 to Marcos Meli - http://www.marcosmeli.com.ar"
// Errors, suggestions, contributions, send a mail to: marcos@filehelpers.com.
#endregion
using System;
namespace FileHelpers
{
/// <summary>Base class for all the library Exceptions.</summary>
public class FileHelpersException : Exception
{
/// <summary>Basic constructor of the exception.</summary>
/// <param name="message">Message of the exception.</param>
public FileHelpersException(string message) : base(message)
{
}
/// <summary>Basic constructor of the exception.</summary>
/// <param name="message">Message of the exception.</param>
/// <param name="innerEx">The inner Exception.</param>
public FileHelpersException(string message, Exception innerEx) : base(message, innerEx)
{
}
}
}

View file

@ -1,113 +0,0 @@
using System;
using System.ComponentModel;
namespace FileHelpers
{
// ---- Read Operations ----
#if NET_1_1
/// <summary>
/// Called in read operations just before the record string is translated to a record.
/// </summary>
/// <param name="engine">The engine that generates the event.</param>
/// <param name="e">The event data.</param>
public delegate void BeforeReadRecordHandler(EngineBase engine, BeforeReadRecordEventArgs e);
/// <summary>
/// Called in read operations just after the record was created from a record string.
/// </summary>
/// <param name="engine">The engine that generates the event.</param>
/// <param name="e">The event data.</param>
public delegate void AfterReadRecordHandler(EngineBase engine, AfterReadRecordEventArgs e);
// ---- Write Operations ----
/// <summary>
/// Called in write operations just before the record is converted to a string to write it.
/// </summary>
/// <param name="engine">The engine that generates the event.</param>
/// <param name="e">The event data.</param>
public delegate void BeforeWriteRecordHandler(EngineBase engine, BeforeWriteRecordEventArgs e);
/// <summary>
/// Called in write operations just after the record was converted to a string.
/// </summary>
/// <param name="engine">The engine that generates the event.</param>
/// <param name="e">The event data.</param>
public delegate void AfterWriteRecordHandler(EngineBase engine, AfterWriteRecordEventArgs e);
#else
/// <summary>
/// Called in read operations just before the record string is translated to a record.
/// </summary>
/// <param name="engine">The engine that generates the event.</param>
/// <param name="e">The event data.</param>
public delegate void BeforeReadRecordHandler<T>(EngineBase engine, BeforeReadRecordEventArgs<T> e);
/// <summary>
/// Called in read operations just after the record was created from a record string.
/// </summary>
/// <param name="engine">The engine that generates the event.</param>
/// <param name="e">The event data.</param>
public delegate void AfterReadRecordHandler<T>(EngineBase engine, AfterReadRecordEventArgs<T> e);
// ---- Write Operations ----
/// <summary>
/// Called in write operations just before the record is converted to a string to write it.
/// </summary>
/// <param name="engine">The engine that generates the event.</param>
/// <param name="e">The event data.</param>
public delegate void BeforeWriteRecordHandler<T>(EngineBase engine, BeforeWriteRecordEventArgs<T> e);
/// <summary>
/// Called in write operations just after the record was converted to a string.
/// </summary>
/// <param name="engine">The engine that generates the event.</param>
/// <param name="e">The event data.</param>
public delegate void AfterWriteRecordHandler<T>(EngineBase engine, AfterWriteRecordEventArgs<T> e);
/// <summary>
/// Called in read operations just before the record string is translated to a record.
/// </summary>
/// <param name="engine">The engine that generates the event.</param>
/// <param name="e">The event data.</param>
public delegate void BeforeReadRecordHandler(EngineBase engine, BeforeReadRecordEventArgs e);
/// <summary>
/// Called in read operations just after the record was created from a record string.
/// </summary>
/// <param name="engine">The engine that generates the event.</param>
/// <param name="e">The event data.</param>
public delegate void AfterReadRecordHandler(EngineBase engine, AfterReadRecordEventArgs e);
// ---- Write Operations ----
/// <summary>
/// Called in write operations just before the record is converted to a string to write it.
/// </summary>
/// <param name="engine">The engine that generates the event.</param>
/// <param name="e">The event data.</param>
public delegate void BeforeWriteRecordHandler(EngineBase engine, BeforeWriteRecordEventArgs e);
/// <summary>
/// Called in write operations just after the record was converted to a string.
/// </summary>
/// <param name="engine">The engine that generates the event.</param>
/// <param name="e">The event data.</param>
public delegate void AfterWriteRecordHandler(EngineBase engine, AfterWriteRecordEventArgs e);
#endif
}

View file

@ -1,139 +0,0 @@
using System;
using System.ComponentModel;
namespace FileHelpers
{
/// <summary>Base class of <see cref="BeforeReadRecordEventArgs"/> and <see cref="AfterReadRecordEventArgs"/></summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public abstract class ReadRecordEventArgs: EventArgs
{
internal ReadRecordEventArgs(string line, int lineNumber)
{
mRecordLine = line;
mLineNumber = lineNumber;
}
private string mRecordLine;
private int mLineNumber;
/// <summary>The current line number.</summary>
public int LineNumber
{
get { return mLineNumber; }
}
/// <summary>The just read record line.</summary>
public string RecordLine
{
get { return mRecordLine; }
}
}
/// <summary>Arguments for the <see cref="BeforeReadRecordHandler"/></summary>
#if NET_1_1
public sealed class BeforeReadRecordEventArgs: ReadRecordEventArgs
#else
public sealed class BeforeReadRecordEventArgs: BeforeReadRecordEventArgs<object>
{
internal BeforeReadRecordEventArgs(string line)
: this(line, -1)
{ }
internal BeforeReadRecordEventArgs(string line, int lineNumber)
: base(line, lineNumber)
{ }
}
/// <summary>Arguments for the <see cref="BeforeReadRecordHandler"/></summary>
public class BeforeReadRecordEventArgs<T> : ReadRecordEventArgs
#endif
{
internal BeforeReadRecordEventArgs(string line): this(line, -1)
{}
internal BeforeReadRecordEventArgs(string line, int lineNumber): base(line, lineNumber)
{}
private bool mSkipThisRecord = false;
/// <summary>Set this property to true if you want to bypass the current line.</summary>
public bool SkipThisRecord
{
get { return mSkipThisRecord; }
set { mSkipThisRecord = value; }
}
}
/// <summary>Arguments for the <see cref="AfterReadRecordHandler"/></summary>
#if NET_1_1
public sealed class AfterReadRecordEventArgs: ReadRecordEventArgs
{
internal AfterReadRecordEventArgs(string line, object newRecord): this(line, newRecord, -1)
{}
internal AfterReadRecordEventArgs(string line, object newRecord, int lineNumber): base(line, lineNumber)
{
mRecord = newRecord;
}
private object mRecord;
/// <summary>The current record.</summary>
public object Record
{
get { return mRecord; }
set { mRecord = value; }
}
#else
public sealed class AfterReadRecordEventArgs: AfterReadRecordEventArgs<object>
{
internal AfterReadRecordEventArgs(string line, object newRecord)
: this(line, newRecord, -1)
{ }
internal AfterReadRecordEventArgs(string line, object newRecord, int lineNumber)
: base(line, newRecord, lineNumber)
{
}
}
/// <summary>Arguments for the <see cref="AfterReadRecordHandler"/></summary>
public class AfterReadRecordEventArgs<T> : ReadRecordEventArgs
{
internal AfterReadRecordEventArgs(string line, T newRecord): this(line, newRecord, -1)
{}
internal AfterReadRecordEventArgs(string line, T newRecord, int lineNumber): base(line, lineNumber)
{
mRecord = newRecord;
}
private T mRecord;
/// <summary>The current record.</summary>
public T Record
{
get { return mRecord; }
set { mRecord = value; }
}
#endif
private bool mSkipThisRecord = false;
/// <summary>Set this property to true if you want to bypass the current record.</summary>
public bool SkipThisRecord
{
get { return mSkipThisRecord; }
set { mSkipThisRecord = value; }
}
}
}

View file

@ -1,125 +0,0 @@
using System;
using System.ComponentModel;
namespace FileHelpers
{
#if NET_1_1
/// <summary>Base class of <see cref="BeforeWriteRecordEventArgs" /> and <see cref="AfterWriteRecordEventArgs" /></summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public abstract class WriteRecordEventArgs: EventArgs
{
internal WriteRecordEventArgs(object record, int lineNumber)
{
mRecord = record;
mLineNumber = lineNumber;
}
#else
/// <summary>Base class of <see cref="BeforeWriteRecordEventArgs&lt;T&gt;"/> and <see cref="AfterWriteRecordEventArgs&lt;T&gt;"/></summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public abstract class WriteRecordEventArgs<T> : EventArgs
{
internal WriteRecordEventArgs(T record, int lineNumber)
{
mRecord = record;
mLineNumber = lineNumber;
}
#endif
#if NET_1_1
private object mRecord;
/// <summary>The current record.</summary>
public object Record
{
get { return mRecord; }
}
#else
private T mRecord;
/// <summary>The current record.</summary>
public T Record
{
get { return mRecord; }
}
#endif
private int mLineNumber;
/// <summary>The current line number.</summary>
public int LineNumber
{
get { return mLineNumber; }
}
}
/// <summary>Arguments for the <see cref="BeforeWriteRecordHandler"/></summary>
#if NET_1_1
public sealed class BeforeWriteRecordEventArgs: WriteRecordEventArgs
{
internal BeforeWriteRecordEventArgs(object record, int lineNumber)
#else
public sealed class BeforeWriteRecordEventArgs: BeforeWriteRecordEventArgs<object>
{
internal BeforeWriteRecordEventArgs(object record, int lineNumber)
: base(record, lineNumber)
{}
}
/// <summary>Arguments for the <see cref="BeforeWriteRecordHandler"/></summary>
public class BeforeWriteRecordEventArgs<T>: WriteRecordEventArgs<T>
{
internal BeforeWriteRecordEventArgs(T record, int lineNumber)
#endif
: base(record, lineNumber)
{}
private bool mSkipThisRecord = false;
/// <summary>Set this property as true if you want to bypass the current record.</summary>
public bool SkipThisRecord
{
get { return mSkipThisRecord; }
set { mSkipThisRecord = value; }
}
}
/// <summary>Arguments for the <see cref="AfterWriteRecordHandler"/></summary>
#if NET_1_1
public sealed class AfterWriteRecordEventArgs: WriteRecordEventArgs
{
internal AfterWriteRecordEventArgs(object record, int lineNumber, string line): base(record, lineNumber)
#else
public sealed class AfterWriteRecordEventArgs: AfterWriteRecordEventArgs<object>
{
internal AfterWriteRecordEventArgs(object record, int lineNumber, string line)
:base(record, lineNumber, line)
{ }
}
/// <summary>Arguments for the <see cref="AfterWriteRecordHandler"/></summary>
public class AfterWriteRecordEventArgs<T>: WriteRecordEventArgs<T>
{
internal AfterWriteRecordEventArgs(T record, int lineNumber, string line): base(record, lineNumber)
#endif
{
mRecordLine = line;
}
private string mRecordLine;
/// <summary>The line to be written to the file. WARNING: you can change this and the engines will write it to the file.</summary>
public string RecordLine
{
get { return mRecordLine; }
set { mRecordLine = value; }
}
}
}

View file

@ -1,182 +0,0 @@
#region " © Copyright 2005-07 to Marcos Meli - http://www.marcosmeli.com.ar"
// Errors, suggestions, contributions, send a mail to: marcos@filehelpers.com.
#endregion
using System;
using System.Globalization;
using System.Reflection;
using System.Text;
namespace FileHelpers
{
internal sealed class DelimitedField : FieldBase
{
#region " Constructor "
internal DelimitedField(FieldInfo fi, string sep) : base(fi)
{
Separator = sep;
}
#endregion
private static CompareInfo mCompare = CultureInfo.InvariantCulture.CompareInfo;
#region " Properties "
private string mSeparator;
internal string Separator
{
get { return mSeparator; }
set
{
mSeparator = value;
if (mIsLast)
mCharsToDiscard = 0;
else
mCharsToDiscard = mSeparator.Length;
}
}
internal char mQuoteChar = '\0';
internal QuoteMode mQuoteMode;
internal MultilineMode mQuoteMultiline = MultilineMode.AllowForBoth;
#endregion
#region " Overrides String Handling "
protected override ExtractedInfo ExtractFieldString(LineInfo line)
{
if (mIsOptional && line.IsEOL() )
return ExtractedInfo.Empty;
if (mQuoteChar == '\0')
return BasicExtractString(line);
else
{
//TODO: UnComment and Fix
if (mTrimMode == TrimMode.Both || mTrimMode == TrimMode.Left)
{
//int pos = line.mCurrentPos;
line.TrimStart(mTrimChars);
// from2 = from.TrimStart(mTrimChars);
//res.CharsRemoved = line.mCurrentPos - pos;
}
string quotedStr = mQuoteChar.ToString();
if (line.StartsWith(quotedStr))
{
// ExtractedInfo res = null;
// res = new ExtractedInfo(line, line.mCurrentPos);
return StringHelper.ExtractQuotedString(line, mQuoteChar, mQuoteMultiline == MultilineMode.AllowForBoth || mQuoteMultiline == MultilineMode.AllowForRead);
// if (mQuoteMultiline == MultilineMode.AllowForBoth || mQuoteMultiline == MultilineMode.AllowForRead)
// {
//
// //res.ExtractedString = ei.ExtractedString;
// //res.CharsRemoved += ei.CharsRemoved;
// //res.ExtraLines = ei.ExtraLines;
// //res.NewRestOfLine = ei.NewRestOfLine;
// }
// else
// {
// return StringHelper.ExtractQuotedString(from2, mQuoteChar, out index);
// //res.CharsRemoved += index;
// }
// return res;
}
else
{
if (mQuoteMode == QuoteMode.OptionalForBoth || mQuoteMode == QuoteMode.OptionalForRead)
return BasicExtractString(line);
else if (line.StartsWithTrim(quotedStr))
throw new BadUsageException("The field '" + this.mFieldInfo.Name + "' has spaces before the QuotedChar at line "+ line.mReader.LineNumber.ToString() + ". Use the TrimAttribute to by pass this error. Field String: " + line.CurrentString);
else
throw new BadUsageException("The field '" + this.mFieldInfo.Name + "' not begin with the QuotedChar at line "+ line.mReader.LineNumber.ToString() + ". You can use FieldQuoted(QuoteMode.OptionalForRead) to allow optional quoted field.. Field String: " + line.CurrentString);
}
}
}
private ExtractedInfo BasicExtractString(LineInfo line)
{
ExtractedInfo res;
if (mIsLast)
res = new ExtractedInfo(line);
else
{
int sepPos;
sepPos = line.IndexOf(mSeparator);
if (sepPos == -1)
{
if (this.mNextIsOptional == false)
{
string msg = null;
if (mIsFirst && line.EmptyFromPos())
msg = "The line " + line.mReader.LineNumber.ToString() + " is empty. Maybe you need to use the attribute [IgnoreEmptyLines] in your record class.";
else
msg = "The delimiter '" + this.mSeparator + "' can´t be found after the field '" + this.mFieldInfo.Name + "' at line " + line.mReader.LineNumber.ToString() + " (the record has less fields, the delimiter is wrong or the next field must be marked as optional).";
throw new FileHelpersException(msg);
}
else
sepPos = line.mLine.Length - 1;
}
res = new ExtractedInfo(line, sepPos);
}
return res;
}
protected override void CreateFieldString(StringBuilder sb, object fieldValue)
{
string field = base.BaseFieldString(fieldValue);
bool hasNewLine = mCompare.IndexOf(field, StringHelper.NewLine) >= 0;
// If have a new line and this is not allowed throw an exception
if (hasNewLine &&
(mQuoteMultiline == MultilineMode.AllowForRead ||
mQuoteMultiline == MultilineMode.NotAllow))
throw new BadUsageException("One value for the field " + this.mFieldInfo.Name + " has a new line inside. To allow write this value you must add a FieldQuoted attribute with the multiline option in true.");
// Add Quotes If:
// - optional == false
// - is optional and contains the separator
// - is optional and contains a new line
if ((mQuoteChar != '\0') &&
(mQuoteMode == QuoteMode.AlwaysQuoted ||
mQuoteMode == QuoteMode.OptionalForRead ||
( (mQuoteMode == QuoteMode.OptionalForWrite || mQuoteMode == QuoteMode.OptionalForBoth)
&& mCompare.IndexOf(field, mSeparator) >= 0) || hasNewLine))
StringHelper.CreateQuotedString(sb, field, mQuoteChar);
else
sb.Append(field);
if (mIsLast == false)
sb.Append(mSeparator);
}
#endregion
}
}

View file

@ -1,352 +0,0 @@
#region " © Copyright 2005-07 to Marcos Meli - http://www.marcosmeli.com.ar"
// Errors, suggestions, contributions, send a mail to: marcos@filehelpers.com.
#endregion
using System;
using System.Reflection;
using System.Text;
namespace FileHelpers
{
/// <summary>Base class for all Field Types. Implements all the basic functionality of a field in a typed file.</summary>
internal abstract class FieldBase
{
#region " Private & Internal Fields "
private static Type strType = typeof (string);
internal Type mFieldType;
internal bool mIsStringField;
internal FieldInfo mFieldInfo;
internal TrimMode mTrimMode = TrimMode.None;
internal Char[] mTrimChars = null;
internal bool mIsOptional = false;
internal bool mNextIsOptional = false;
internal bool mInNewLine = false;
internal bool mIsFirst = false;
internal bool mIsLast = false;
internal bool mTrailingArray = false;
internal object mNullValue = null;
//internal bool mNullValueOnWrite = false;
#if NET_2_0
private bool mIsNullableType = false;
#endif
#endregion
#region " Constructor "
protected FieldBase(FieldInfo fi)
{
mFieldInfo = fi;
mFieldType = mFieldInfo.FieldType;
mIsStringField = mFieldType == strType;
object[] attribs = fi.GetCustomAttributes(typeof (FieldConverterAttribute), true);
if (attribs.Length > 0)
{
FieldConverterAttribute conv = (FieldConverterAttribute)attribs[0];
mConvertProvider = conv.Converter;
conv.ValidateTypes(mFieldInfo);
}
else
mConvertProvider = ConvertHelpers.GetDefaultConverter(fi.Name, mFieldType);
if (mConvertProvider != null)
mConvertProvider.mDestinationType = fi.FieldType;
attribs = fi.GetCustomAttributes(typeof (FieldNullValueAttribute), true);
if (attribs.Length > 0)
{
mNullValue = ((FieldNullValueAttribute) attribs[0]).NullValue;
// mNullValueOnWrite = ((FieldNullValueAttribute) attribs[0]).NullValueOnWrite;
if (mNullValue != null)
{
if (! mFieldType.IsAssignableFrom(mNullValue.GetType()))
throw new BadUsageException("The NullValue is of type: " + mNullValue.GetType().Name +
" that is not asignable to the field " + mFieldInfo.Name + " of type: " +
mFieldType.Name);
}
}
#if NET_2_0
mIsNullableType = mFieldType.IsValueType &&
mFieldType.IsGenericType &&
mFieldType.GetGenericTypeDefinition() == typeof(Nullable<>);
#endif
}
#endregion
private static char[] WhitespaceChars = new char[]
{
'\t', '\n', '\v', '\f', '\r', ' ', '\x00a0', '\u2000', '\u2001', '\u2002', '\u2003', '\u2004', '\u2005', '\u2006', '\u2007', '\u2008',
'\u2009', '\u200a', '\u200b', '\u3000', '\ufeff'
};
#region " MustOverride (String Handling) "
protected abstract ExtractedInfo ExtractFieldString(LineInfo line);
protected abstract void CreateFieldString(StringBuilder sb, object fieldValue);
protected string BaseFieldString(object fieldValue)
{
if (mConvertProvider == null)
{
if (fieldValue == null)
return string.Empty;
else
return fieldValue.ToString();
// else if (mNullValueOnWrite && fieldValue.Equals(mNullValue))
// res = string.Empty;
}
else
{
return mConvertProvider.FieldToString(fieldValue);
}
}
protected int mCharsToDiscard = 0;
#endregion
internal ConverterBase mConvertProvider;
#region " ExtractValue "
// object[] values, int index, ForwardReader reader
internal object ExtractValue(LineInfo line)
{
//-> extract only what I need
if (this.mInNewLine == true)
{
if (line.EmptyFromPos() == false)
throw new BadUsageException("Text '" + line.CurrentString +
"' found before the new line of the field: " + mFieldInfo.Name +
" (this is not allowed when you use [FieldInNewLine])");
line.ReLoad(line.mReader.ReadNextLine());
if (line.mLineStr == null)
throw new BadUsageException("End of stream found parsing the field " + mFieldInfo.Name +
". Please check the class record.");
}
ExtractedInfo info = ExtractFieldString(line);
if (info.mCustomExtractedString == null)
line.mCurrentPos = info.ExtractedTo + 1;
line.mCurrentPos += mCharsToDiscard; //total;
return AssignFromString(info, line);
//-> discard the part that I use
//TODO: Uncoment this for Quoted Handling
// if (info.NewRestOfLine != null)
// {
// if (info.NewRestOfLine.Length < CharsToDiscard())
// return info.NewRestOfLine;
// else
// return info.NewRestOfLine.Substring(CharsToDiscard());
// }
// else
// {
// int total;
// if (info.CharsRemoved >= line.mLine.Length)
// total = line.mLine.Length;
// else
// total = info.CharsRemoved + CharsToDiscard();
//return buffer.Substring(total);
// }
}
#region " AssignFromString "
internal object AssignFromString(ExtractedInfo fieldString, LineInfo line)
{
object val;
switch (mTrimMode)
{
case TrimMode.None:
break;
case TrimMode.Both:
fieldString.TrimBoth(mTrimChars);
break;
case TrimMode.Left:
fieldString.TrimStart(mTrimChars);
break;
case TrimMode.Right:
fieldString.TrimEnd(mTrimChars);
break;
}
try
{
if (mConvertProvider == null)
{
if (mIsStringField)
val = fieldString.ExtractedString();
else
{
// Trim it to use Convert.ChangeType
fieldString.TrimBoth(WhitespaceChars);
if (fieldString.Length == 0)
{
// Empty stand for null
val = GetNullValue();
}
else
{
val = Convert.ChangeType(fieldString.ExtractedString(), mFieldType, null);
}
}
}
else
{
if (mConvertProvider.CustomNullHandling == false &&
fieldString.HasOnlyThisChars(WhitespaceChars))
{
val = GetNullValue();
}
else
{
string from = fieldString.ExtractedString();
val = mConvertProvider.StringToField(from);
if (val == null)
val = GetNullValue();
}
}
return val;
}
catch (ConvertException ex)
{
throw ConvertException.ReThrowException(ex, mFieldInfo.Name, line.mReader.LineNumber, fieldString.ExtractedFrom + 1);
}
}
private object GetNullValue()
{
if (mNullValue == null)
{
if (mFieldType.IsValueType)
{
#if NET_2_0
if ( mIsNullableType )
return null;
throw new BadUsageException("Null Value found for the field '" + mFieldInfo.Name + "' in the class '" +
mFieldInfo.DeclaringType.Name +
"'. You must specify a FieldNullValue attribute because this is a ValueType and can´t be null or you can use the Nullable Types feature of the .NET framework.");
#else
throw new BadUsageException("Null Value found for the field '" + mFieldInfo.Name + "' in the class '" +
mFieldInfo.DeclaringType.Name +
"'. You must specify a FieldNullValueAttribute because this is a ValueType and can´t be null.");
#endif
}
else
return null;
}
else
return mNullValue;
}
#endregion
#region " CreateValueForField "
public object CreateValueForField(object fieldValue)
{
object val = null;
if (fieldValue == null)
{
if (mNullValue == null)
{
if (mFieldType.IsValueType)
throw new BadUsageException("Null Value found. You must specify a NullValueAttribute in the " + mFieldInfo.Name +
" field of type " + mFieldInfo.FieldType.Name + ", because this is a ValueType.");
else
val = null;
}
else
{
val = mNullValue;
}
}
else if (mFieldType == fieldValue)
val = fieldValue;
else
{
if (mConvertProvider == null)
val = Convert.ChangeType(fieldValue, mFieldType, null);
else
{
try
{
val = Convert.ChangeType(fieldValue, mFieldType, null);
}
catch
{
val = mConvertProvider.StringToField(fieldValue.ToString());
}
}
}
return val;
}
#endregion
#endregion
#region " AssignToString "
internal void AssignToString(StringBuilder sb, object fieldValue)
{
if (this.mInNewLine == true)
sb.Append(StringHelper.NewLine);
CreateFieldString(sb, fieldValue);
}
#endregion
}
}

View file

@ -1,122 +0,0 @@
#region " © Copyright 2005-07 to Marcos Meli - http://www.marcosmeli.com.ar"
// Errors, suggestions, contributions, send a mail to: marcos@filehelpers.com.
#endregion
using System.Reflection;
namespace FileHelpers
{
internal sealed class FieldFactory
{
#region " Avoid Creation "
private FieldFactory()
{
}
#endregion
public static FieldBase CreateField(FieldInfo fi, TypedRecordAttribute recordAttribute, bool someOptional)
{
// If ignored, return null
if (fi.IsDefined(typeof (FieldIgnoredAttribute), true))
return null;
FieldBase res = null;
FieldAttribute[] attributes;
FieldAttribute fieldAttb;
attributes = (FieldAttribute[]) fi.GetCustomAttributes(typeof (FieldAttribute), true);
// CHECK USAGE ERRORS !!!
if (attributes.Length > 1)
throw new BadUsageException("The field: " + fi.Name + " has more than one FieldAttribute (left only one or none)");
if (attributes.Length == 0 && recordAttribute is FixedLengthRecordAttribute)
throw new BadUsageException("The record class marked with the FixedLengthRecord attribute must include a FixedLength attribute in each field.");
if (recordAttribute is DelimitedRecordAttribute && fi.IsDefined(typeof (FieldAlignAttribute), true))
throw new BadUsageException("The AlignAttribute is only valid for fixed length records and are used only for write purpouse.");
// PROCESS IN NORMAL CONDITIONS
if (attributes.Length > 0)
{
fieldAttb = attributes[0];
if (fieldAttb is FieldFixedLengthAttribute)
{
if (recordAttribute is DelimitedRecordAttribute)
throw new BadUsageException("The FieldFixedLengthAttribute is only for the FixedLengthRecords not for the delimited ones.");
FieldFixedLengthAttribute attb = ((FieldFixedLengthAttribute) fieldAttb);
FieldAlignAttribute[] alignAttbs = (FieldAlignAttribute[]) fi.GetCustomAttributes(typeof (FieldAlignAttribute), true);
FieldAlignAttribute align = null;
if (alignAttbs.Length > 0)
align = alignAttbs[0];
res = new FixedLengthField(fi, attb.Length, align);
((FixedLengthField) res).mFixedMode = ((FixedLengthRecordAttribute)recordAttribute).mFixedMode;
}
else if (fieldAttb is FieldDelimiterAttribute)
{
if (recordAttribute is FixedLengthRecordAttribute)
throw new BadUsageException("The DelimitedAttribute is only for DelimitedRecords not for the fixed ones.");
res = new DelimitedField(fi, ((FieldDelimiterAttribute) fieldAttb).mSeparator);
}
else
throw new BadUsageException("Custom TypedRecords not currently supported.");
}
else // attributes.Length == 0
{
if (recordAttribute is DelimitedRecordAttribute)
res = new DelimitedField(fi, ((DelimitedRecordAttribute) recordAttribute).Separator);
}
//----- TRIMMING
if (res != null)
{
FieldTrimAttribute[] trim = (FieldTrimAttribute[]) fi.GetCustomAttributes(typeof (FieldTrimAttribute), true);
if (trim.Length > 0)
{
res.mTrimMode = trim[0].TrimMode;
res.mTrimChars = trim[0].TrimChars;
}
FieldQuotedAttribute[] quotedAttributes = (FieldQuotedAttribute[]) fi.GetCustomAttributes(typeof (FieldQuotedAttribute), true);
if (quotedAttributes.Length > 0)
{
if (res is FixedLengthField)
throw new BadUsageException("The QuotedAttribute can't be used in FixedLength fields.");
((DelimitedField) res).mQuoteChar = quotedAttributes[0].QuoteChar;
((DelimitedField) res).mQuoteMode = quotedAttributes[0].QuoteMode;
((DelimitedField) res).mQuoteMultiline = quotedAttributes[0].QuoteMultiline;
}
FieldOptionalAttribute[] optionalAttribs = (FieldOptionalAttribute[]) fi.GetCustomAttributes(typeof (FieldOptionalAttribute), true);
if (optionalAttribs.Length > 0)
res.mIsOptional = true;
else if (someOptional)
throw new BadUsageException("When you define a field as FieldOptional, the next fields must be marked with the same attribute. ( Try adding [FieldOptional] to " + res.mFieldInfo.Name + " )");
res.mInNewLine = fi.IsDefined(typeof(FieldInNewLineAttribute), true);
}
return res;
}
}
}

View file

@ -1,112 +0,0 @@
#region " © Copyright 2005-07 to Marcos Meli - http://www.marcosmeli.com.ar"
// Errors, suggestions, contributions, send a mail to: marcos@filehelpers.com.
#endregion
using System.Reflection;
using System;
using System.Text;
namespace FileHelpers
{
internal sealed class FixedLengthField : FieldBase
{
#region " Properties "
internal int mFieldLength;
internal FieldAlignAttribute mAlign = new FieldAlignAttribute(AlignMode.Left, ' ');
internal FixedMode mFixedMode = FixedMode.ExactLength;
#endregion
#region " Constructor "
internal FixedLengthField(FieldInfo fi, int length, FieldAlignAttribute align) : base(fi)
{
this.mFieldLength = length;
if (align != null)
this.mAlign = align;
else
{
if (fi.FieldType == typeof(Int16) ||
fi.FieldType == typeof(Int32) ||
fi.FieldType == typeof(Int64) ||
fi.FieldType == typeof(UInt16) ||
fi.FieldType == typeof(UInt32) ||
fi.FieldType == typeof(UInt64) ||
fi.FieldType == typeof(byte) ||
fi.FieldType == typeof(sbyte) ||
fi.FieldType == typeof(decimal) ||
fi.FieldType == typeof(float) ||
fi.FieldType == typeof(double))
mAlign = new FieldAlignAttribute(AlignMode.Right, ' ');
}
}
#endregion
#region " Overrides String Handling "
protected override ExtractedInfo ExtractFieldString(LineInfo line)
{
if (line.CurrentLength == 0)
{
if (mIsOptional)
return ExtractedInfo.Empty;
else
throw new BadUsageException("End Of Line found processing the field: " + mFieldInfo.Name + " at line "+ line.mReader.LineNumber.ToString() + ". (You need to mark it as [FieldOptional] if you want to avoid this exception)");
}
ExtractedInfo res;
if (line.CurrentLength < this.mFieldLength)
if (mFixedMode == FixedMode.AllowLessChars || mFixedMode == FixedMode.AllowVariableLength)
res = new ExtractedInfo(line);
else
throw new BadUsageException("The string '" + line.CurrentString + "' (length " + line.CurrentLength.ToString() + ") at line "+ line.mReader.LineNumber.ToString() + " has less chars than the defined for " + mFieldInfo.Name + " (" + mFieldLength.ToString() + "). You can use the [FixedLengthRecord(FixedMode.AllowLessChars)] to avoid this problem.");
else if (mIsLast && line.CurrentLength > mFieldLength && mFixedMode != FixedMode.AllowMoreChars && mFixedMode != FixedMode.AllowVariableLength)
throw new BadUsageException("The string '" + line.CurrentString + "' (length " + line.CurrentLength.ToString() + ") at line "+ line.mReader.LineNumber.ToString() + " has more chars than the defined for the last field " + mFieldInfo.Name + " (" + mFieldLength.ToString() + ").You can use the [FixedLengthRecord(FixedMode.AllowMoreChars)] to avoid this problem.");
else
res = new ExtractedInfo(line, line.mCurrentPos + mFieldLength);
return res;
}
protected override void CreateFieldString(StringBuilder sb, object fieldValue)
{
string field = base.BaseFieldString(fieldValue);
if (field.Length > mFieldLength)
field = field.Substring(0, mFieldLength);
//sb.Length = length + this.mFieldLength;
if (mAlign.Align == AlignMode.Left)
{
sb.Append(field);
sb.Append(mAlign.AlignChar, mFieldLength - field.Length);
}
else if (mAlign.Align == AlignMode.Right)
{
sb.Append(mAlign.AlignChar, mFieldLength - field.Length);
sb.Append(field);
}
else
{
int middle = (mFieldLength - field.Length) / 2;
sb.Append(mAlign.AlignChar, middle);
sb.Append(field);
sb.Append(mAlign.AlignChar, mFieldLength - field.Length - middle);
// if (middle > 0)
// res = res.PadLeft(mFieldLength - middle, mAlign.AlignChar).PadRight(mFieldLength, mAlign.AlignChar);
}
}
#endregion
}
}

View file

@ -1,3 +0,0 @@
[InternetShortcut]
URL=http://www.amazon.com/gp/registry/wishlist/20HRDZWS0NJ6C/104-5286383-8923129?reveal=unpurchased&filter=all&sort=priority&layout=standard&x=10&y=9

View file

@ -1,3 +0,0 @@
[InternetShortcut]
URL=mailto:marcos@filehelpers.com?subject=FileHelpers%20Feedback

View file

@ -1,3 +0,0 @@
[InternetShortcut]
URL=http://sourceforge.net/project/showfiles.php?group_id=152382

View file

@ -1,3 +0,0 @@
[InternetShortcut]
URL=http://www.filehelpers.com/forums/

View file

@ -1,3 +0,0 @@
[InternetShortcut]
URL=http://www.filehelpers.com

View file

@ -1,31 +0,0 @@
using System;
namespace FileHelpers
{
internal sealed class ConditionHelper
{
private ConditionHelper()
{}
public static bool BeginsWith(string line, string selector)
{
return line.StartsWith(selector);
}
public static bool EndsWith(string line, string selector)
{
return line.EndsWith(selector);
}
public static bool Contains(string line, string selector)
{
return line.IndexOf(selector) >= 0;
}
public static bool Enclosed(string line, string selector)
{
return line.StartsWith(selector) && line.EndsWith(selector);
}
}
}

View file

@ -1,53 +0,0 @@
#region " © Copyright 2005-07 to Marcos Meli - http://www.marcosmeli.com.ar"
// Errors, suggestions, contributions, send a mail to: marcos@filehelpers.com.
#endregion
using System;
namespace FileHelpers
{
internal sealed class ExHelper
{
private ExHelper()
{
}
public static void CheckNullOrEmpty(string val)
{
if (val == null || val.Length == 0)
throw new ArgumentNullException("Value can´t be null or empty");
}
public static void CheckNullOrEmpty(string val, string paramName)
{
if (val == null || val.Length == 0)
throw new ArgumentNullException(paramName, "Value can´t be null or empty");
}
public static void CheckNullParam(string param, string paramName)
{
if (param == null || param.Length == 0)
throw new ArgumentNullException(paramName + " can´t be neither null nor empty", paramName);
}
public static void CheckNullParam(object param, string paramName)
{
if (param == null)
throw new ArgumentNullException(paramName + " can´t be null", paramName);
}
public static void CheckDifferentsParams(object param1, string param1Name, object param2, string param2Name)
{
if (param1 == param2)
throw new ArgumentException(param1Name + " can´t be the same that " + param2Name, param1Name + " and " + param2Name);
}
public static void PositiveValue(int val)
{
if (val < 0 )
throw new ArgumentException("The value must be greater or equal than 0.");
}
}
}

View file

@ -1,44 +0,0 @@
#region " © Copyright 2005-07 to Marcos Meli - http://www.marcosmeli.com.ar"
// Errors, suggestions, contributions, send a mail to: marcos@filehelpers.com.
#endregion
using System;
namespace FileHelpers
{
internal sealed class ProgressHelper
{
private ProgressHelper()
{}
public static void Notify(ProgressChangeHandler handler, ProgressMode mode, int current, int total)
{
if (handler == null)
return;
if (mode == ProgressMode.DontNotify)
return;
switch(mode)
{
case ProgressMode.NotifyBytes:
handler(new ProgressEventArgs(mode, current, total));
break;
case ProgressMode.NotifyRecords:
handler(new ProgressEventArgs(mode, current, total));
break;
case ProgressMode.NotifyPercent:
if (total == -1)
return;
handler(new ProgressEventArgs(mode, (int) (current*100/total), 100));
break;
}
}
}
}

View file

@ -1,84 +0,0 @@
#region " © Copyright 2005-07 to Marcos Meli - http://www.marcosmeli.com.ar"
// Errors, suggestions, contributions, send a mail to: marcos@filehelpers.com.
#endregion
using System.IO;
using System.Text;
namespace FileHelpers
{
#if NET_1_1 || MINI
internal sealed class StreamHelper
{
private StreamHelper()
{
}
#else
internal static class StreamHelper
{
#endif
internal static TextWriter CreateFileAppender(string fileName, Encoding encode, bool correctEnd)
{
return CreateFileAppender(fileName, encode, correctEnd, true);
}
internal static TextWriter CreateFileAppender(string fileName, Encoding encode, bool correctEnd, bool disposeStream)
{
TextWriter res;
if (correctEnd)
{
FileStream fs = null;
try
{
fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
if (fs.Length >= 2)
{
fs.Seek(-2, SeekOrigin.End);
if (fs.ReadByte() == 13)
{
if (fs.ReadByte() == 10)
{
int nowRead;
do
{
fs.Seek(-2, SeekOrigin.Current);
nowRead = fs.ReadByte();
} while (nowRead == 13 || nowRead == 10);
}
}
else
fs.ReadByte();
fs.WriteByte(13);
fs.WriteByte(10);
}
res = new StreamWriter(fs, encode);
}
finally
{
if (disposeStream && fs != null)
fs.Close();
}
}
else
{
res = new StreamWriter(fileName, true, encode);
}
return res;
}
}
}

View file

@ -1,220 +0,0 @@
#region " © Copyright 2005-07 to Marcos Meli - http://www.marcosmeli.com.ar"
// Errors, suggestions, contributions, send a mail to: marcos@filehelpers.com.
#endregion
using System;
using System.ComponentModel;
using System.Text;
namespace FileHelpers
{
internal sealed class StringHelper
{
private StringHelper()
{
}
#if ! MINI
internal static readonly string NewLine = Environment.NewLine;
#else
internal static readonly string NewLine = "\r\n";
#endif
#region " ExtractQuotedString "
internal static ExtractedInfo ExtractQuotedString(LineInfo line, char quoteChar, bool allowMultiline)
{
// if (line.mReader == null)
// throw new BadUsageException("The reader can´t be null");
if (line.IsEOL())
throw new BadUsageException("An empty String found and can be parsed like a QuotedString try to use SafeExtractQuotedString");
if (line.mLine[line.mCurrentPos] != quoteChar)
throw new BadUsageException("The source string not begins with the quote char: " + quoteChar);
StringBuilder res = new StringBuilder(32);
//int lines = 0;
bool firstFound = false;
int i = line.mCurrentPos + 1;
//bool mustContinue = true;
while (line.mLineStr != null)
{
while (i < line.mLine.Length)
{
if (line.mLine[i] == quoteChar)
{
if (firstFound == true)
{
// Is an escaped quoted char
res.Append(quoteChar);
firstFound = false;
}
else
{
firstFound = true;
}
}
else
{
if (firstFound)
{
// This was the end of the string
line.mCurrentPos = i;
return new ExtractedInfo(res.ToString());
// ExtractedInfo ei = ;
// return ei;
}
else
{
res.Append(line.mLine[i]);
}
}
i++;
}
if (firstFound)
{
line.mCurrentPos = i;
return new ExtractedInfo(res.ToString());
}
else
{
if (allowMultiline == false)
throw new BadUsageException("The current field has an UnClosed quoted string. Complete line: " + res.ToString());
line.ReadNextLine();
res.Append(StringHelper.NewLine);
//lines++;
i = 0;
}
}
throw new BadUsageException("The current field has an unclosed quoted string. Complete Filed String: " + res.ToString());
}
#endregion
#region " CreateQuotedString "
internal static void CreateQuotedString(StringBuilder sb, string source, char quoteChar)
{
if (source == null) source = string.Empty;
string quotedCharStr = quoteChar.ToString();
string escapedString = source.Replace(quotedCharStr, quotedCharStr + quotedCharStr);
sb.Append(quoteChar);
sb.Append(escapedString);
sb.Append(quoteChar);
}
#endregion
#region " RemoveBlanks "
internal static string RemoveBlanks(string source)
{
StringBuilder sb = null;
int i = 0;
while (i < source.Length && Char.IsWhiteSpace(source[i]))
{
i++;
}
if (i < source.Length && (source[i] == '+' || source[i] == '-'))
{
i++;
while (i < source.Length && Char.IsWhiteSpace(source[i]))
{
if (sb == null)
sb = new StringBuilder(source[i-1].ToString());
i++;
}
}
if (sb == null)
return source;
else if (i < source.Length)
sb.Append(source.Substring(i));
return sb.ToString();
}
#endregion
//
// #region " ExtractQuotedString "
//
// internal static string ExtractQuotedString(string source, char quoteChar, out int index)
// {
// StringBuilder res = new StringBuilder(32);
// bool beginEscape = false;
//
//
// if (source == null || source.Length == 0)
//
//
// throw new BadUsageException("An empty String found and can be parsed like a QuotedString try to use SafeExtractQuotedString");
//
//
// if (source[0] != quoteChar)
// throw new BadUsageException("The source string not begins with the quote char: " + quoteChar);
//
// index = 0;
// int i = 1;
// while (i < source.Length)
// {
// if (source[i] == quoteChar)
// {
// if (beginEscape == true)
// {
// beginEscape = false;
// res.Append(quoteChar);
// }
// else
// {
// beginEscape = true;
// }
// }
// else
// {
// if (beginEscape)
// {
// // End of the String
// index = i;
// return res.ToString();
// }
// else
// {
// res.Append(source[i]);
// }
// }
//
// i++;
// }
// if (beginEscape)
// {
// index = i;
// return res.ToString();
// }
// else
// throw new BadUsageException("The current field has an UnClosed quoted string. Complete line: " + source);
// }
//
// #endregion
}
}

View file

@ -1,65 +0,0 @@
using System;
namespace FileHelpers
{
/// <summary>
/// Interface used to provide In record notification of read operations.
/// </summary>
/// <example>
/// <code>
/// private class SampleType: INotifyRead, INotifyWrite
/// { ....
///
/// public void AfterRead(EngineBase engine, string line)
/// {
/// // Your Code Here
/// }
/// public void BeforeWrite(EngineBase engine)
/// {
/// // Your Code Here
/// }
///
/// }
/// </code>
/// </example>
public interface INotifyRead
{
/// <summary>
/// Method called by the engines after read a record from the source data.
/// </summary>
/// <param name="engine">The engine that makes the call.</param>
/// <param name="line">The source line.</param>
void AfterRead(EngineBase engine, string line);
}
/// <summary>
/// Interface used to provide <b>In record notification of write operations.</b>
/// </summary>
/// <example>
/// <code>
/// private class SampleType: INotifyRead, INotifyWrite
/// { ....
///
/// public void AfterRead(EngineBase engine, string line)
/// {
/// // Your Code Here
/// }
/// public void BeforeWrite(EngineBase engine)
/// {
/// // Your Code Here
/// }
///
/// }
/// </code>
/// </example>
public interface INotifyWrite
{
/// <summary>
/// Method called by the engines before write a record to the destination stream.
/// </summary>
/// <param name="engine">The engine that makes the call.</param>
void BeforeWrite(EngineBase engine);
}
}

View file

@ -1,509 +0,0 @@
The FileHelpers are licensed under the GNU LESSER GENERAL PUBLIC LICENSE
That allow commercial and non commercial developments under this terms:
-----------------------------------------------------------------------
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
not price. Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Libraries
If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change. You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).
To apply these terms, attach the following notices to the library. It is
safest to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
<one line to give the library's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Also add information on how to contact you by electronic and paper mail.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the
library `Frob' (a library for tweaking knobs) written by James Random Hacker.
<signature of Ty Coon>, 1 April 1990
Ty Coon, President of Vice
That's all there is to it!

View file

@ -1,122 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{1AAA2739-D853-41B0-866B-B55B373616E1}</ProjectGuid>
<ProjectTypeGuids>{EFBA0AD7-5A72-4C68-AF49-83D382785DCF};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>MonoDroid.FileHelpers</RootNamespace>
<AssemblyName>MonoDroid.FileHelpers</AssemblyName>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="mscorlib" />
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Data" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Attributes\ConditionalRecordAttribute.cs" />
<Compile Include="Attributes\DelimitedRecordAttribute.cs" />
<Compile Include="Attributes\FieldAlignAttribute.cs" />
<Compile Include="Attributes\FieldAttribute.cs" />
<Compile Include="Attributes\FieldConverterAttribute.cs" />
<Compile Include="Attributes\FieldDelimiterAttribute.cs" />
<Compile Include="Attributes\FieldFixedLengthAttribute.cs" />
<Compile Include="Attributes\FieldIgnoredAttribute.cs" />
<Compile Include="Attributes\FieldInNewLineAttribute.cs" />
<Compile Include="Attributes\FieldNullValueAttribute.cs" />
<Compile Include="Attributes\FieldOptionalAttribute.cs" />
<Compile Include="Attributes\FieldQuotedAttribute.cs" />
<Compile Include="Attributes\FieldTrimAttribute.cs" />
<Compile Include="Attributes\FixedLengthRecordAttribute.cs" />
<Compile Include="Attributes\IgnoreCommentedLinesAttribute.cs" />
<Compile Include="Attributes\IgnoreEmptyLinesAttribute.cs" />
<Compile Include="Attributes\IgnoreFirstAttribute.cs" />
<Compile Include="Attributes\IgnoreLastAttribute.cs" />
<Compile Include="Converters\ConverterBase.cs" />
<Compile Include="Converters\ConvertHelpers.cs" />
<Compile Include="Converters\EnumConverter.cs" />
<Compile Include="Core\ExtractInfo.cs" />
<Compile Include="Core\ForwardReader.cs" />
<Compile Include="Core\LineInfo.cs" />
<Compile Include="Core\RecordInfo.cs" />
<Compile Include="Engines\EngineBase.cs" />
<Compile Include="Engines\FileHelperEngine.cs" />
<Compile Include="Enums\AlignMode.cs" />
<Compile Include="Enums\ConverterKind.cs" />
<Compile Include="Enums\ErrorMode.cs" />
<Compile Include="Enums\FixedMode.cs" />
<Compile Include="Enums\MultilineMode.cs" />
<Compile Include="Enums\ProgressMode.cs" />
<Compile Include="Enums\QuoteMode.cs" />
<Compile Include="Enums\RecordCondition.cs" />
<Compile Include="Enums\TrimMode.cs" />
<Compile Include="ErrorHandling\BadUsageException.cs" />
<Compile Include="ErrorHandling\ConvertException.cs" />
<Compile Include="ErrorHandling\ErrorInfo.cs" />
<Compile Include="ErrorHandling\ErrorManager.cs" />
<Compile Include="ErrorHandling\FileHelpersException.cs" />
<Compile Include="Events\Delegates.cs" />
<Compile Include="Events\ReadEventArgs.cs" />
<Compile Include="Events\WriteEventArgs.cs" />
<Compile Include="Fields\DelimitedField.cs" />
<Compile Include="Fields\FieldBase.cs" />
<Compile Include="Fields\FieldFactory.cs" />
<Compile Include="Fields\FixedLengthField.cs" />
<Compile Include="Helpers\ConditionHelper.cs" />
<Compile Include="Helpers\ExHelper.cs" />
<Compile Include="Helpers\ProgressHelper.cs" />
<Compile Include="Helpers\StreamHelper.cs" />
<Compile Include="Helpers\StringHelper.cs" />
<Compile Include="Interfaces\INotificableRecord.cs" />
<Compile Include="Options\DelimitedRecordOptions.cs" />
<Compile Include="Options\FixedRecordOptions.cs" />
<Compile Include="Options\RecordOptions.cs" />
<Compile Include="Progress\ProgressChange.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Attributes\TypedRecordAttribute.cs" />
</ItemGroup>
<ItemGroup>
<Content Include="DevNotes.txt" />
<Content Include="LGPL - License.txt" />
</ItemGroup>
<ItemGroup>
<None Include="FileHelpers - Amazon Whish List.url" />
<None Include="FileHelpers - Contact Me.url" />
<None Include="FileHelpers - Download Source Code.url" />
<None Include="FileHelpers - Forums.url" />
<None Include="FileHelpers - Home Page.url" />
</ItemGroup>
<Import Project="$(MSBuildExtensionsPath)\Novell\Novell.MonoDroid.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View file

@ -0,0 +1,71 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{1AAA2739-D853-41B0-866B-B55B373616E1}</ProjectGuid>
<ProjectTypeGuids>{EFBA0AD7-5A72-4C68-AF49-83D382785DCF};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>LumenWorks.Framework.IO.Csv</RootNamespace>
<AssemblyName>MonoDroid.LumenWorks.Framework.IO.Csv</AssemblyName>
<FileAlignment>512</FileAlignment>
<AndroidSupportedAbis>armeabi</AndroidSupportedAbis>
<AndroidStoreUncompressedFileExtensions />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="mscorlib" />
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Data" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="Csv\CachedCsvReader.cs" />
<Compile Include="Csv\CachedCsvReader.CsvBindingList.cs" />
<Compile Include="Csv\CachedCsvReader.CsvPropertyDescriptor.cs" />
<Compile Include="Csv\CachedCsvReader.CsvRecordComparer.cs" />
<Compile Include="Csv\CsvReader.cs" />
<Compile Include="Csv\CsvReader.DataReaderValidations.cs" />
<Compile Include="Csv\CsvReader.RecordEnumerator.cs" />
<Compile Include="Csv\Events\ParseErrorEventArgs.cs" />
<Compile Include="Csv\Exceptions\MalformedCsvException.cs" />
<Compile Include="Csv\Exceptions\MissingFieldCsvException.cs" />
<Compile Include="Csv\MissingFieldAction.cs" />
<Compile Include="Csv\ParseErrorAction.cs" />
<Compile Include="Csv\Resources\ExceptionMessage.Designer.cs" />
<Compile Include="Csv\ValueTrimmingOptions.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Csv\Resources\ExceptionMessage.resx" />
</ItemGroup>
<Import Project="$(MSBuildExtensionsPath)\Novell\Novell.MonoDroid.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

View file

@ -1,35 +0,0 @@
using System;
namespace FileHelpers
{
/// <summary>
/// This class allows you to set some options of the delimited records but at runtime.
/// With this options the library is more flexible than never.
/// </summary>
public sealed class DelimitedRecordOptions: RecordOptions
{
internal DelimitedRecordOptions(RecordInfo info)
:base(info)
{
}
/// <summary>
/// The delimiter used to identify each field in the data.
/// </summary>
public string Delimiter
{
get
{
return ((DelimitedField) mRecordInfo.mFields[0]).Separator;
}
set
{
for(int i = 0; i < mRecordInfo.mFieldCount ;i++)
((DelimitedField) mRecordInfo.mFields[i]).Separator = value;
}
}
}
}

View file

@ -1,63 +0,0 @@
using System;
using System.Diagnostics;
namespace FileHelpers
{
/// <summary>
/// This class allows you to set some options of the fixed length records but at runtime.
/// With this options the library is more flexible than never.
/// </summary>
public sealed class FixedRecordOptions: RecordOptions
{
internal FixedRecordOptions(RecordInfo info)
:base(info)
{
}
/// <summary>Indicates the behavior when variable length records are found in a [<see cref="FixedLengthRecordAttribute"/>]. (Note: nothing in common with [FieldOptional])</summary>
public FixedMode FixedMode
{
get
{
return ((FixedLengthField) mRecordInfo.mFields[0]).mFixedMode;
}
set
{
for(int i = 0; i < mRecordInfo.mFieldCount; i++)
{
((FixedLengthField) mRecordInfo.mFields[i]).mFixedMode = value;
}
}
}
#if NET_2_0
[DebuggerDisplay("FileHelperEngine for type: {RecordType.Name}. ErrorMode: {ErrorManager.ErrorMode.ToString()}. Encoding: {Encoding.EncodingName}")]
#endif
private int mRecordLength = int.MinValue;
/// <summary>
/// The sum of the indivial field lengths.
/// </summary>
public int RecordLength
{
get
{
if (mRecordLength != int.MinValue)
return mRecordLength;
mRecordLength = 0;
foreach (FixedLengthField field in mRecordInfo.mFields)
{
mRecordLength += field.mFieldLength;
}
return mRecordLength;
}
}
}
}

View file

@ -1,134 +0,0 @@
using System;
using System.Diagnostics;
using System.ComponentModel;
namespace FileHelpers
{
/// <summary>
/// This class allows you to set some options of the records but at runtime.
/// With this options the library is more flexible than never.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public abstract class RecordOptions
{
#if NET_2_0
[DebuggerDisplay("FileHelperEngine for type: {RecordType.Name}. ErrorMode: {ErrorManager.ErrorMode.ToString()}. Encoding: {Encoding.EncodingName}")]
#endif
internal RecordInfo mRecordInfo;
internal RecordOptions(RecordInfo info)
{
mRecordInfo = info;
mRecordConditionInfo = new RecordConditionInfo(info);
mIgnoreCommentInfo = new IgnoreCommentInfo(info);
}
/// <summary>Indicates the number of first lines to be discarded.</summary>
public int IgnoreFirstLines
{
get { return mRecordInfo.mIgnoreFirst; }
set
{
ExHelper.PositiveValue(value);
mRecordInfo.mIgnoreFirst= value;
}
}
/// <summary>Indicates the number of lines at the end of file to be discarded.</summary>
public int IgnoreLastLines
{
get { return mRecordInfo.mIgnoreLast; }
set
{
ExHelper.PositiveValue(value);
mRecordInfo.mIgnoreLast = value;
}
}
/// <summary>Indicates that the engine must ignore the empty lines while reading.</summary>
public bool IgnoreEmptyLines
{
get { return mRecordInfo.mIgnoreEmptyLines; }
set { mRecordInfo.mIgnoreEmptyLines= value; }
}
private RecordConditionInfo mRecordConditionInfo;
/// <summary>Allow to tell the engine what records must be included or excluded while reading.</summary>
public RecordConditionInfo RecordCondition
{
get { return mRecordConditionInfo; }
}
private IgnoreCommentInfo mIgnoreCommentInfo;
/// <summary>Indicates that the engine must ignore the lines with this comment marker.</summary>
public IgnoreCommentInfo IgnoreCommentedLines
{
get { return mIgnoreCommentInfo; }
}
/// <summary>Allow to tell the engine what records must be included or excluded while reading.</summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public sealed class RecordConditionInfo
{
RecordInfo mRecordInfo;
internal RecordConditionInfo(RecordInfo ri)
{
mRecordInfo = ri;
}
/// <summary>The condition used to include or exclude records.</summary>
public RecordCondition Condition
{
get { return mRecordInfo.mRecordCondition; }
set { mRecordInfo.mRecordCondition = value; }
}
/// <summary>The selector used by the <see cref="RecordCondition"/>.</summary>
public string Selector
{
get { return mRecordInfo.mRecordConditionSelector; }
set { mRecordInfo.mRecordConditionSelector = value; }
}
}
/// <summary>Indicates that the engine must ignore the lines with this comment marker.</summary>
[EditorBrowsable(EditorBrowsableState.Advanced)]
public sealed class IgnoreCommentInfo
{
RecordInfo mRecordInfo;
internal IgnoreCommentInfo(RecordInfo ri)
{
mRecordInfo = ri;
}
/// <summary>
/// <para>Indicates that the engine must ignore the lines with this comment marker.</para>
/// <para>An emty string or null indicates that the engine dont look for comments</para>
/// </summary>
public string CommentMarker
{
get { return mRecordInfo.mCommentMarker; }
set
{
if (value != null)
value = value.Trim();
mRecordInfo.mCommentMarker = value;
}
}
/// <summary>Indicates if the comment can have spaces or tabs at left (true by default)</summary>
public bool InAnyPlace
{
get { return mRecordInfo.mCommentAnyPlace; }
set { mRecordInfo.mCommentAnyPlace = value; }
}
}
}
}

View file

@ -1,49 +0,0 @@
namespace FileHelpers
{
#if ! MINI
/// <summary>Class used to notify the current progress position and other context info.</summary>
public class ProgressEventArgs
{
internal ProgressEventArgs(ProgressMode mode, int current, int total)
{
mProgressMode = mode;
mProgressCurrent = current;
mProgressTotal = total;
}
internal ProgressEventArgs()
{
mProgressMode = ProgressMode.DontNotify;
}
private int mProgressCurrent;
private int mProgressTotal;
private ProgressMode mProgressMode = ProgressMode.DontNotify;
/// <summary>The current progress position. Check also the ProgressMode property.</summary>
public int ProgressCurrent
{
get { return mProgressCurrent; }
}
/// <summary>The total when the progress finish. (<b>-1 means undefined</b>)</summary>
public int ProgressTotal
{
get { return mProgressTotal; }
}
/// <summary>The ProgressMode used.</summary>
public ProgressMode ProgressMode
{
get { return mProgressMode; }
}
}
/// <summary>Delegate used to notify progress to the user.</summary>
/// <param name="e">The Event args with information about the progress.</param>
public delegate void ProgressChangeHandler(ProgressEventArgs e);
#endif
}

View file

@ -1,20 +1,28 @@
using System.Reflection;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MonoDroid.FileHelpers")]
[assembly: AssemblyTitle("LumenWorks.Framework.IO")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("MonoDroid.FileHelpers")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2011")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("LumenWorks.Framework.IO")]
[assembly: AssemblyCopyright("Copyright © 2005 Sébastien Lorion")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: System.CLSCompliant(true)]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("a8577790-f852-47a5-94ec-ec5fdf155a55")]
// Version information for an assembly consists of the following four values:
//
// Major Version
@ -22,8 +30,7 @@ using System.Runtime.InteropServices;
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyVersion("3.7.1.0")]
[assembly: AssemblyFileVersion("3.7.1.0")]

View file

@ -0,0 +1,5 @@
This is a MonoDroid version of the LumenWorks CSV parser, by Sébastien Lorion
It's under the MIT License.
For more information: http://www.codeproject.com/KB/database/CsvReader.aspx

View file

@ -34,6 +34,7 @@
<Reference Include="Mono.Android" />
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Data" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Xml" />
</ItemGroup>
@ -49,7 +50,9 @@
<Compile Include="Services\IPortfolioService.cs" />
<Compile Include="Services\PortfolioService.cs" />
<Compile Include="StockData\CsvParser.cs" />
<Compile Include="StockData\GoogleStockDataProvider.cs" />
<Compile Include="StockData\GoogleStockDataProvider.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="StockData\IStockDataProvider.cs" />
<Compile Include="StockData\YahooFinanceStockData.cs">
<SubType>Code</SubType>
@ -59,9 +62,9 @@
</Compile>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\MonoDroid.FileHelpers\MonoDroid.FileHelpers.csproj">
<ProjectReference Include="..\MonoDroid.FileHelpers\MonoDroid.LumenWorks.Framework.IO.Csv.csproj">
<Project>{1AAA2739-D853-41B0-866B-B55B373616E1}</Project>
<Name>MonoDroid.FileHelpers</Name>
<Name>MonoDroid.LumenWorks.Framework.IO.Csv</Name>
</ProjectReference>
<ProjectReference Include="..\MonoStockPortfolio.Entities\MonoStockPortfolio.Entities.csproj">
<Project>{05A57650-3B41-46FF-9EAD-9112B5EFBEED}</Project>

View file

@ -1,29 +1,21 @@
using FileHelpers;
namespace MonoStockPortfolio.Core.StockData
{
[DelimitedRecord(",")]
public class YahooFinanceStockData
{
[FieldQuoted(QuoteMode.OptionalForBoth)]
public string Ticker;
public decimal LastTradePrice;
[FieldQuoted(QuoteMode.OptionalForBoth)]
public string Name;
public string Volume;
public decimal Change;
[FieldQuoted(QuoteMode.OptionalForBoth)]
public string LastTradeTime;
[FieldQuoted(QuoteMode.OptionalForBoth)]
public string RealTimeLastTradeWithTime;
[FieldQuoted(QuoteMode.OptionalForBoth)]
public string ChangeRealTime;
}
}

View file

@ -4,7 +4,7 @@ using System.IO;
using System.Linq;
using System.Net;
using Android.Util;
using FileHelpers;
using LumenWorks.Framework.IO.Csv;
using MonoStockPortfolio.Entities;
namespace MonoStockPortfolio.Core.StockData
@ -67,16 +67,24 @@ namespace MonoStockPortfolio.Core.StockData
return stock;
}
private static IList<YahooFinanceStockData> ParseCsvIntoStockQuotes(string csv)
private static IEnumerable<YahooFinanceStockData> ParseCsvIntoStockQuotes(string csv)
{
var engine = new FileHelperEngine(typeof(YahooFinanceStockData));
var stockQuotes = engine.ReadString(csv) as YahooFinanceStockData[];
stockQuotes.ToList().ForEach(q => Log.Error("ParseCSV",q.Volume));
if (stockQuotes == null)
using(var csvReader = new CsvReader(new StringReader(csv),false))
{
throw new ArgumentException("Could not parse CSV input");
while(csvReader.ReadNextRecord())
{
var d = new YahooFinanceStockData();
d.Ticker = csvReader[0];
d.LastTradePrice = decimal.Parse(csvReader[1]);
d.Name = csvReader[2];
d.Volume = csvReader[3];
d.Change = decimal.Parse(csvReader[4]);
d.LastTradeTime = csvReader[5];
d.RealTimeLastTradeWithTime = csvReader[6];
d.ChangeRealTime = csvReader[7];
yield return d;
}
}
return stockQuotes;
}
private static string ScrapeUrl(string url)

View file

@ -1,5 +1,10 @@
using System;
using System.Collections.Generic;
using System.Linq;
using MonoStockPortfolio.Core.PortfolioRepositories;
using MonoStockPortfolio.Core.Services;
using MonoStockPortfolio.Core.StockData;
using MonoStockPortfolio.Entities;
using Xunit;
namespace MonoStockPortfolio.Tests
@ -7,11 +12,84 @@ namespace MonoStockPortfolio.Tests
public class YahooStockDataProviderTests
{
[Fact]
public void Can_get_volume()
public void Can_get_volume_from_web()
{
var svc = new YahooStockDataProvider();
var quote = svc.GetStockQuotes(new[] {"XIN"}).Single();
Assert.True(!string.IsNullOrEmpty(quote.Volume));
var quotes = svc.GetStockQuotes(new[] {"GOOG", "AMZN", "AAPL", "MSFT", "NOVL", "S", "VZ", "T"});
foreach (var stockQuote in quotes)
{
Assert.True(!string.IsNullOrEmpty(stockQuote.Volume));
}
Assert.True(quotes.Any());
}
[Fact]
public void Can_get_volume_from_service()
{
var svc = new PortfolioService(BuildStubPortfolioRepo(), new YahooStockDataProvider());
var items = svc.GetDetailedItems(1, new List<StockDataItem> {StockDataItem.Ticker, StockDataItem.Volume});
foreach (var positionResultsViewModel in items)
{
Assert.True(positionResultsViewModel.Items[StockDataItem.Volume] != null);
}
Assert.True(items.Any());
}
private IPortfolioRepository BuildStubPortfolioRepo()
{
return new StubPortfolioRepo();
}
public class StubPortfolioRepo : IPortfolioRepository
{
public IList<Position> GetAllPositions(long portfolioId)
{
return new List<Position>
{
new Position(1)
{ContainingPortfolioID = 1, PricePerShare = 5, Shares = 100, Ticker = "GOOG"}
};
}
public IList<Portfolio> GetAllPortfolios()
{
throw new NotImplementedException();
}
public void SavePortfolio(Portfolio portfolio)
{
throw new NotImplementedException();
}
public void DeletePortfolioById(int portfolioId)
{
throw new NotImplementedException();
}
public Portfolio GetPortfolioById(long portfolioId)
{
throw new NotImplementedException();
}
public Portfolio GetPortfolioByName(string portfolioName)
{
throw new NotImplementedException();
}
public void SavePosition(Position position)
{
throw new NotImplementedException();
}
public void DeletePositionById(long positionId)
{
throw new NotImplementedException();
}
public Position GetPositionById(long positionId)
{
throw new NotImplementedException();
}
}
}
}

View file

@ -15,7 +15,7 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MonoStockPortfolio.Entities
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MonoStockPortfolio.Tests", "MonoStockPortfolio.Tests\MonoStockPortfolio.Tests.csproj", "{C2797FAB-AFAB-49F6-9131-FC9BF03CAB9D}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MonoDroid.FileHelpers", "MonoDroid.FileHelpers\MonoDroid.FileHelpers.csproj", "{1AAA2739-D853-41B0-866B-B55B373616E1}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MonoDroid.LumenWorks.Framework.IO.Csv", "MonoDroid.FileHelpers\MonoDroid.LumenWorks.Framework.IO.Csv.csproj", "{1AAA2739-D853-41B0-866B-B55B373616E1}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution

View file

@ -14,7 +14,7 @@ namespace MonoStockPortfolio.Framework
static ServiceLocator()
{
IttyBittyIoC.Register<IStockDataProvider>(() => new YahooStockDataProvider());
IttyBittyIoC.Register<IPortfolioService>(() => new PortfolioService(new AndroidSqlitePortfolioRepository(Context), new GoogleStockDataProvider()));
IttyBittyIoC.Register<IPortfolioService>(() => new PortfolioService(new AndroidSqlitePortfolioRepository(Context), new YahooStockDataProvider()));
IttyBittyIoC.Register<IPortfolioRepository>(() => new AndroidSqlitePortfolioRepository(Context));
IttyBittyIoC.Register<IConfigRepository>(() => new AndroidSqliteConfigRepository(Context));
}

BIN
libs/FileHelpers.dll Normal file

Binary file not shown.