Click button to edit
Events And Notification: Before/After Write Event Handling
Show how to implement write events
Input.txt
10249 TOMSP 05071996 11.61
10250 HANAR 08071996 0.00
10251 VICTE 08071996 41.34
10269 TOMSP 05071996 11.61
10230 HANAR 08071996 65.83
10151 VICTE 08071996 41.34
Report layout.cs
[FixedLengthRecord]
[IgnoreEmptyLines]
public class OrdersFixed
{
[FieldFixedLength(7)]
public int OrderID;
[FieldFixedLength(8)]
public string CustomerID;
[FieldFixedLength(8)]
public DateTime OrderDate;
[FieldFixedLength(11)]
public decimal Freight;
}
Run a record through engine using the write event to filter out unwanted details
RunEngine.cs
public override void Run()
{
var engine = new FileHelperEngine<OrdersFixed>();
var result = engine.ReadFile("Input.txt");
// add our filter logic.
engine.BeforeWriteRecord += BeforeWriteEvent;
engine.AfterWriteRecord += AfterWriteEvent;
engine.WriteFile("output.txt", result);
}
private void BeforeWriteEvent(EngineBase engine, BeforeWriteEventArgs<OrdersFixed> e)
{
// We only want clients with large frieght values
if (e.Record.Freight < 40)
e.SkipThisRecord = true;
}
private void AfterWriteEvent(EngineBase engine, AfterWriteEventArgs<OrdersFixed> e)
{
// Hide a line
if (e.Record.CustomerID.Trim() == "HANAR")
e.RecordLine = "-- Insufficient Access";
}
output.txt
10251 VICTE 08071996 41.34
-- Insufficient Access
10151 VICTE 08071996 41.34
ImportantYou can use lambda expressions instead of event methods, for example:
RunEngineLambda.cs
public void RunLambda()
{
var engine = new FileHelperEngine<OrdersFixed>();
var result = engine.ReadFile("Input.txt");
// add our filter logic.
engine.BeforeWriteRecord += (eng, e) => {
if (e.Record.Freight < 40)
e.SkipThisRecord = true;
};
engine.AfterWriteRecord += (eng, e) => {
if (e.Record.CustomerID == "HANAR")
e.RecordLine = "Insufficient Access";
};
engine.WriteFile("output.txt", result);
}