Retrieving private member variables during validation

Retrieving private member variables during validation

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


JonM posted on Friday, November 23, 2007

Current I'm using C# and the Utilities.CallByName function to retrieve public properties in my validation functions.  I need to retrieve a private variables in a couple of different rules and do not want to expose them as public members.  Everytime I try it I get an "Object reference not set to an instance of an object." error.  Any ideas here?

William replied on Friday, November 23, 2007

If you are defining your rule method inside the corresponding business object, you can access the private members directly. For example,

[Serializable]
public class Customer : BusinessBase<Customer>
{
  private string _name;
  ...
  private static bool NameValidation(Customer target, RuleArgs e)
  {
    return target._name != null && target._name.Trim().Length > 0;
  }
}

 

ayubu replied on Saturday, November 24, 2007

It depends

if the property you want to access set/gets an value which belongs to another user defined object that will be created later by your class through the constructor( for child objects) , then you will face the message since the validation rules are bound to the object before it is even created i.e when the base business classes are created.

RockfordLhotka replied on Monday, November 26, 2007

William is correct - if the rule method is in your business class then you can access the fields directly. And if you use the generic overloads for rules (as discussed in the CSLA .NET Version 2.1 Handbook) then you can access the fields off the target parameter.

However, if your rule method is not in the business class, then you have a bigger challenge. You can then either use reflection (which is what the Utilities method uses, but it only works on properties, so you'd have to write your own variation to use fields - and accessing private fields via reflection is pretty slow so make sure to test). Or you can use an interface to expose the values.

For an example of using an interface, look at ProjectTracker.Library and how IHoldRoles is used.

Copyright (c) Marimer LLC