Welcome to weblogs.com.pk Sign in | Join | Help

Data Validation–Silverlight

exploits_of_a_mom.pngThere was a little “applet” made in Silverlight and was deployed in Sharepoint; it has been running fine until recently when there is some change in Government Rules requiring data entry operators to punch in few extra numbers that need to be required and are in certain pattern. We had the data entry fields already in place but back then the rules were not that strict and requirements were not that clear around those fields and data in these fields were not being validated “that much”!

Sadly Silverlight code was bit old and the data validation logic was not based on System.ComponentModel.DataAnnotations and there was also a concern that as Silverlight is “out” and HTML5/JS/CSS3 are “in” we had to keep the balance in our efforts. Using the WCF RIA Services technique of reusing the model with add existing item and linking the code file to same thing in client side and server code we managed to have consistent data model classes with appropriate Data Annotations.

image

Once these classes are in place; we can use Silverlight Data Binding feature and Data Validation Controls by having a fake data context object like so:

image

With such arrangements in place; data binding validation and validation control will work with the newly introduced data annotations and its up to us to either use the .DataContext object or control properties (or even both) in the code behind!

Code:
public MainPage()
{
    InitializeComponent();
    User u = new User();
    this.GridUser.DataContext = u;

    this.ButtonSubmit.Click += delegate
    {
        var user = this.GridUser.DataContext as User;
        try
        {
            //for required attribute validation etc
            Validator.ValidateObject(user, new ValidationContext(user));
            /*
                * now its upto us we can use user object. do something with it;
                * submit to server etc or use its properties or use controls for
                * values like this.TextBoxUserName.Text etc
                */
        }
        catch (Exception ex)
        {
            this.ValidationControl.Errors.Add(new ValidationSummaryItem(ex.Message));
        }
    };
}

Published Friday, December 04, 2015 2:11 PM by khurram
Filed under: ,

Comments

No Comments

New Comments to this post are disabled