Tuesday 24 January 2012

Async Validation - Calling server validation from client async

Lets define our example:
  • Project name: SLUsers
  • Domain Service: Domain
  • Entity: Users
    •  UserID
    •  UserName
    •  Password
We need to check the availability of the UserName while the person is still filling the registration form.


Step #1
======
In the Server App, in your Domain Service create the following :

        [Invoke]
        public bool IsUserNameUsed(string userName)
        {
            Users _users = null;
            using (DomainEntities domainEntity = new DomainEntities())
            {
                _users = domainEntity.Users.Where(s => s.UserName == userName).SingleOrDefault();
            }
            return _users != null;
        }
 
 
Step #2
======
In the Silverlight Client App, in the Model folder add new class and paste the following:
 
 
using System.ComponentModel.DataAnnotations;
using SLUsers.Web.Services;
using System.ServiceModel.DomainServices.Client;
namespace SLUsers.Web.Models
{
    public partial class Users
    {
        private ValidationResult _isUserNameUsedValidationResult;
        partial void OnUserNameChanged()
        {
           if (IsDeserializing)
               return;
            DomainContext context = new DomainContext();
            context.IsUserNameUsed(UserName,
                delegate(InvokeOperation<bool> isUsed)
                {
                    if (isUsed.Value)
                    {
                        _isUserNameUsedValidationResult = new ValidationResult("Username already exist in database !", new string[] {"UserName"});
                         
                        ValidationErrors.Add(_isUserNameUsedValidationResult);
                    }
                }, null);
        }
         
    }
}
 
 
 
Notes
=====
1- The class created in Step #2 in the client application have the name space SLUsers.Web.Models which referes to the Web.
2- The part which triggers the validation lies in the step #2 in the line:
 _isUserNameUsedValidationResult = new ValidationResult("Username already exist in database !", new string[] {"UserName"});
 where the field name to be validated is 'Username' as:
  new string[] {"UserName"}.
3- In XAML page binding, don't forget to raise the validation error as:
 Text="{Binding Path=UserName, Mode=TwoWay, NotifyOnValidationError=True, UpdateSourceTrigger=PropertyChanged}"
Have a nice day :)