OK I figured out how to do this, but in the end it turned out that the answer opened a rather large can of worms.
Adding the Async rule to your business class:
protected override void AddBusinessRules()
{
base.AddBusinessRules();
ValidationRules.AddRule(UserNameIsUniqueAsync, new AsyncRuleArgs(UserRefProperty, NameProperty));
}
The first arg for AddRule is a delegate shown below:
private static void UserNameIsUniqueAsync(AsyncValidationRuleContext context)
{
DuplicateUserNameCommand command = new DuplicateUserNameCommand((int)context.PropertyValues["UserRef"], context.PropertyValues["Name"].ToString());
DataPortal<DuplicateUserNameCommand> dp = new DataPortal<DuplicateUserNameCommand>();
dp.ExecuteCompleted += (o, e) =>
{
if (e.Error != null)
{
context.OutArgs.Description = "Error checking for duplicate user name. " + e.Error.ToString();
context.OutArgs.Severity = RuleSeverity.Error;
context.OutArgs.Result = false;
}
else
{
if (e.Object.IsDuplicate)
{
context.OutArgs.Description = "Duplicate user name.";
context.OutArgs.Severity = RuleSeverity.Error;
context.OutArgs.Result = false;
}
else
{
context.OutArgs.Result = true;
}
}
context.Complete();
System.Diagnostics.Debug.WriteLine("Context.Complete()");
};
dp.BeginExecute(command);
}
The delegate in turn calls a DuplicateUserNameCommand which is new type you need to create:
[Serializable]
public class DuplicateUserNameCommand : CommandBase
{
private int _userRef;
private string _userName;
private bool _isDuplicate;
public DuplicateUserNameCommand(int userRef, string userName)
{
_userRef = userRef;
_userName = userName;
}
public bool IsDuplicate
{
get { return _isDuplicate; }
private set { _isDuplicate = value; }
}
protected override void DataPortal_Execute()
{
// Check for an existing user in the database with the same username
var repository = new NHibernateUserDAORepository();
var existingUser = repository.FindByUserName(_userName);
if (existingUser != null && existingUser.UserRef != _userRef)
{
_isDuplicate = true;
}
else
{
_isDuplicate = false;
}
}
}
That's about it. The problem that I encountered is that all the code in Command's DataPortal_Execute needs to be thread safe. In my case this caused severak issues so for now I'm reverting back to synchronous rules.