Is it OK to "break" an object during Save()?

Is it OK to "break" an object during Save()?

Old forum URL: forums.lhotka.net/forums/t/5066.aspx


rsbaker0 posted on Monday, July 07, 2008

I'm just wondering if I will run into trouble if I deliberately break (e.g. via a validation rule) an object during the execution of Save().

In this particular care, I'm porting an ungainly legacy transaction to our new CSLA-based framework, and the legacy goes through a long series of "pre-transaction" checks before proceeding, and just sets an error message if something is found wrong. Of course, some of this could be moved to individual rules, but currently there are two many interdepencies between the items for me to safely refactor these out, so I need to leave the original logic intact for the moment.

The old object had an "ErrorMessage" property that it was setting, so I just added a new validation rule on this property that basically says, if the property has a value, then the rule fails, otherwise the rules passes.

All the plumbing seems to work fine -- the UI replaces the existing object with the "broken" one returned over the data portal, and I can get the error indicator to show fine next to a "status" type property.

Am I overlooking a potential gotcha?

RockfordLhotka replied on Monday, July 07, 2008

No, that is an acceptable thing to do in CSLA .NET - the brokenrules collection flows across the data portal just fine. The only thing to watch out for is that the transactional technologies (TransactionScope or EnterpriseServices) usually do a rollback because of an exception - so you'll have to manually manage your own transactions so as to not throw an exception (and thus return the broken object as a result).

Fwiw, it probably won't work in CSLA Light, because the brokenrules collection won't flow across the data portal in that environment.

An alternative approach (very similar to what you have) is to

  1. create a custom exception class, where the exception contains the ErrorMessage value
  2. throw this custom exception in case of failure on the server
  3. override the Save() method in your object and have it catch this custom exception - remember that the Save() method runs on the client
  4. in the Save() method, if the custom exception is caught, do this
    1. set your object's ErrorMessage field
    2. call CheckRules() to run the rule you already have
    3. return this/Me - not the result of the data portal call

This technique will work in CSLA .NET and CSLA Light, because it doesn't depend on the brokenrules collection moving across the wire, and it avoids possible transaction rollback issues on the server.

 

Copyright (c) Marimer LLC