Data Validataion and Broken Rules

This topic discusses data validation, how and when to save objects, and what to do if items aren’t valid.

First you should check to see if your objects need to be saved by evaluating the property .IsSavable. The code below creates a customer object, sets the name and number, and then saves. Before we save though, we check the IsSavable property.

// Add customer
BusinessPartner cust = BusinessPartner.NewBusinessPartner(PartnerTypes.Customer);
cust.Name = "Customer Name";
cust.PartnerNumber = "999999";

// If not savable
if (cust.IsSavable)
{
    // Check the rules
}

If an object isn’t savable then something is wrong. In the UI you’ll be able to see this with the red error icons appearing, and hovering over them will display the error. You won’t be able to save an object until IsSavable is true. To determine what’s wrong programmatically, you’ll use a collection on the object named BrokenRulesCollection. If an object isn’t savable, you can traverse the collection of BrokenRules like below. This allows you to programmatically fix the problem but is also handy with debugging.

// Check the rules
foreach (Avontus.Core.Validation.BrokenRule rule in cust.BrokenRulesCollection)
{
    if (rule.Property == "Name")
    {
        // Fix the name here
    }
}

The ToString() method of the BrokenRulesCollection will return a string with each error on a separate line.

One other thing to keep in mind is that sometimes rules aren’t broken until you try to save an object. In the case of a customer or vendor, the number could be duplicate but we won’t know until a save occurs. To find this out, we need to retrieve the object back from the save and then traverse the rules. This is seen in the sample code below

if (cust.IsSavable)
{
    try
    {
        // Attempt to save
        cust.Save();
    }
    catch (DataPortalException ex)
    {
        // Get the object back from the data tier
        cust = ex.BusinessObject as BusinessPartner;
                
        // We can check to see if the name is unique
        if (!cust.IsUnique)
        {
            // Fix the name
        }
        else
        {
            // Check the rules
        }
    }
}