Evaluating constraints

Before updating the database with changes to your objects it is wise to check that the object is in a valid state first.  ECO allows you to model constraints against your classes by adding a list of OCL expressions, but does not evaluate the expressions at any point.

It is in fact the responsibility of the application to check whether or not an object is valid or invalid, and to then decide what to do about it.  One approach is to check the validity of each object before it is saved, this can be achieved in the UpdateDatabase() method of your EcoSpace.

using Borland.Eco.Services;

...

//Get the serviceIDirtyListService
dirtyList =
  (IDirtyListService) EcoSpace.GetEcoService(typeof(IDirtyListService));

//Process each modified object
if (dirtyList.HasDirtyObjects)
{
  foreach (IObject dirtyObject in dirtyList.AllDirtyObjects as IList)
  {
    ...
  }
}

Now that we have a method of finding all modified objects before they are updated to the database, we just need to check the constraints of each object and throw an exception if any of the objects are in an invalid state.

using Borland.Eco.UmlRt;
using Borland.Eco.Services;

...


//Get the OCL service
IOclService oclService =
  (IOclService) EcoSpace.GetEcoService(typeof(IOclService));

//Evaluate each constraint of the current object
for (Int32 constraintIndex = 0;
   constraintIndex <= dirtyObject.UmlType.Constraints.Count;
  constraintIndex++)
  {
    IConstraint constraint =
      dirtyObject.UmlType.Constraints[constraintIndex];
    bool isValid =
      (bool) oclService.EvaluateAndSubscribe(dirtyObject,
        constraint.Body.Body, null, null).AsObject;

    if (isValid.AsObject)
      throw new Exception(constraint.Name);}
  }
}

TIP: I would recommend setting the "Allow null" property of each attribute to "True", even it the attribute will be required.  You may then add a constraint to your class so that a null value is handled in the same way as any other violation. 

 

In addition, you may change whether or not an attribute is required by modifying the constraints, whereas the AllowNull setting creates a database constraint which is not added/dropped by ECO when you evolve your database.

 

Share this article!

Follow us!

Find more helpful articles: