Use of "RecordCondition.ExcludeIfMatchRegex"

43 views Asked by At

Library version: v2.0.0.0

I would like to use ExcludeIfMatchRegex to exclude certain lines in the input file.

I have tested next code but the system is displaying the usual message error Object reference not set to an instance of an object. If I remove the line containing "ConditionalRecord", the system reads the file and returns the usual validation messages.

using FileHelpers;
using System;

[IgnoreEmptyLines()]
[ConitionalRecord(RecordCondition.ExcludeIfMatchRegex, "[0-9 A-Za-z.,]{1}S[0-9 A-Za-z.,]{10}")] 
[FixedLengthRecord(FixedMode.ExactLength)]
public sealed class PurchaseOrder : INotifyRead
{
    [FieldFixedLength(1)]
    [FieldTrim(TrimMode.Both)]
    public string C;
        
    [FieldFixedLength(1)]
    [FieldTrim(TrimMode.Both)]
    public string A;
        
    [FieldFixedLength(10)]
    [FieldTrim(TrimMode.Both)]
    public string item;

    public void AfterRead(EngineBase engine, string line)
    {
          // not exist the property "SkipThisRecord"??
    }
}
1

There are 1 answers

1
shamp00 On

Looks like a small bug in the 2.0.0.0 library.

When the FileHelpers engine reads a file but ALL lines are excluded AND the class is decorated with INotifyRead it throws the Object Reference error.

However you can work around it by using the AfterReadRecord event instead.

[IgnoreEmptyLines()]
[ConditionalRecord(RecordCondition.ExcludeIfMatchRegex, "[0-9 A-Za-z.,]{1}S[0-9 A-Za-z.,]{10}")]
[FixedLengthRecord(FixedMode.ExactLength)]
public sealed class PurchaseOrder
{
    [FieldFixedLength(1)]
    [FieldTrim(TrimMode.Both)]
    public string C;

    [FieldFixedLength(1)]
    [FieldTrim(TrimMode.Both)]
    public string A;

    [FieldFixedLength(10)]
    [FieldTrim(TrimMode.Both)]
    public string item;
}

internal class Program
{
    static void Main(string[] args)
    {
        FileHelperEngine engine = new FileHelperEngine(typeof(PurchaseOrder));
        // use the AfterReadRecord event instead of the INotifyRead interface
        engine.AfterReadRecord += Engine_AfterReadRecord;

        // The record will be skipped because of the Regex
        var records = engine.ReadString("0S0123456789");
        Debug.Assert(records.Length == 0);

        Console.Write("All OK. No records were imported.");
        Console.ReadKey();
    }

    // Define the event here instead of in your FileHelpers class
    private static void Engine_AfterReadRecord(EngineBase engine, AfterReadRecordEventArgs e)
    {
        // not exist the property "SkipThisRecord"??
    }