Skip to content

Before each Record

Roger Hill edited this page Aug 11, 2019 · 1 revision

Record Processing in FluentCRM

When writing a FluentCRM statement to process a set of records, there is a pattern that can be used to good effect, however, it does come with some potential pitfalls that we may need to avoid.

Consider:

var firstName = String.Empty;
var lastName = String.Empty;
FluentContact.Contact().All()
        .UseAttribute<string>((s) => firstName = s, "firstname")
        .UseAttribute<string>((s) => lastName = s, "lastname")
        .WeakUpdate( "longname", () = return string.join(" ",firstName, lastName))
        .Execute();

This takes all contacts, concatenates the first and last names and uses them to update "long name"

So, what could go wrong?

Ask yourself, what would happen if an existing contact record had a first or last name with a null value?

Remember that The closure in UseAttribute is only called when a non-null, non-empty value is found.

So if the first record is "John Smith" and the second record is " Jones", the closure on firstname will not be called for the second record and the result of this that the second record will be set to a long name of "John Jones"

What can we do about this? Ideally we would like to ensure that the first and second names are set to empty before each record. This is where "BeforeEachRecord" comes in. This allows us to reset any values before each record is read. (Or indeed to carry out any other required action before each record)

The following will do what we expect.

var firstName = String.Empty;
var lastName = String.Empty;
FluentContact.Contact().All()
        .BeforeEachRecord( (e) =>
        {
             firstName = String.Empty;
             lastName = String.Empty;
        }
        .UseAttribute<string>((s) => firstName = s, "firstname")
        .UseAttribute<string>((s) => lastName = s, "lastname")
        .WeakUpdate( "longname", () = return string.join(" ",firstName, lastName))
        .Execute();

AfterEachRecord( (Action action) performs a similar function (after each record has been processed)