有没有人有一个在csla中实现异步验证规则的简单示例?
我在Rolodex示例中查看了Company类中的示例,但这对我来说并不是特别清楚:为什么我需要一个命令类?
我在WPF应用程序中使用csla 3.8。
答案 0 :(得分:1)
好的,我知道如何做到这一点,但最终结果证明答案打开了一大堆蠕虫。
将Async规则添加到您的商家类:
protected override void AddBusinessRules()
{
base.AddBusinessRules();
ValidationRules.AddRule(UserNameIsUniqueAsync, new AsyncRuleArgs(UserRefProperty, NameProperty));
}
AddRule的第一个arg是一个如下所示的委托:
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);
}
委托又调用DuplicateUserNameCommand,这是您需要创建的新类型:
[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;
}
}
}
就是这样。我遇到的问题是Command的DataPortal_Execute中的所有代码都需要是线程安全的。在我的情况下,这导致了severak问题,所以现在我又回到了同步规则。