Wednesday, December 9, 2009

Silverlight 3 : Enable and Disable Validation For Control.

Please check previous post about validation with silverlight.

Enable and Disable Validation or you can say manually adding and remove binding for control.

In previous post i bound myName TextBox to Name property of Customer, But some case you do not want to validate that control and to do so you need to clear binding. ( Simplest way as per my thinking).

1. Remove Binding in Silverlight or Disable Validation

// Clear all errors from validation summary. ( Review previous post XAML)

valida.Errors.Clear();

// Set Text to clear ( As per your need )
myName.Text = String.Empty;

//This call will cleae binding for TextProperty( Take any dependency property)
myName.SetValue(TextBox.TextProperty, DependencyProperty.UnsetValue);
            myName.ClearValue(TextBox.TextProperty);

2. Adding Binding in Silverlight or Enable Validation.

Binding binding = new Binding("Name");
           binding.ValidatesOnExceptions = true;
           binding.NotifyOnValidationError = true;
           binding.Mode = BindingMode.TwoWay;
           myName.SetBinding(TextBox.TextProperty, binding);


Let me know your comment on this.

Silverlight 3 : Validation

To do validation in silverlight 3 , need to use dataannotation. In my previous post i discussed about binding and resource file.

1. Sample XAML File.

<UserControl xmlns:dataInput="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data.Input"  xmlns:dataFormToolkit="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data.DataForm.Toolkit"  x:Class="SilverlightApplication2.MainPage"    xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:controlsToolkit="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Toolkit"    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:SilverlightApplication2.Resourses" xmlns:localCustom="clr-namespace:SilverlightApplication2"
    mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">
    <UserControl.Resources>
        <local:Strings x:Key="LocStrings"></local:Strings>
        <localCustom:DisplayLabelConvertor x:Key="display"></localCustom:DisplayLabelConvertor>
    </UserControl.Resources>
    <Grid x:Name="LayoutRoot" Background="#FF333333">     
        <StackPanel Orientation="Vertical" x:Name="MyDataForm" BindingValidationError="MyDataForm_BindingValidationError" >
            <dataInput:ValidationSummary x:Name="valida" Height="100"></dataInput:ValidationSummary>     

            <TextBox x:Name="myName" Text="{Binding Name,Mode=TwoWay,ValidatesOnExceptions=True,NotifyOnValidationError=True}" >
            </TextBox>         
                <Button Content="save" Click="Button_Click"></Button>
        </StackPanel>
    </Grid>
</UserControl>

2. CS File.

public partial class MainPage : UserControl
    {
        Customer c = new Customer();
        private int _errorCount = 0;
        public MainPage()
        {
            InitializeComponent();       
            MyDataForm.DataContext = c;
        }

        private void MyDataForm_BindingValidationError(object sender, ValidationErrorEventArgs e)
        {
            if (e.Action == ValidationErrorEventAction.Added)
                _errorCount++;
            else if (e.Action == ValidationErrorEventAction.Removed)
                _errorCount--;
        }     

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            _errorCount = 0;

            // Need to do for validating control.
            // If you do not do this then untill you make any change in control no validation will work.
            // Like form first time open and you prees submit then it will not validate . To do so this is required.
            BindingExpression exp = myName.GetBindingExpression(TextBox.TextProperty);
            if (exp != null)
            exp.UpdateSource();

            if (_errorCount ==0)
            {
                //Success
            }
            else
            {
                //Error
            }
        }

    }

3. Enjoy Validation………… :)

Let me know your comment.

Sunday, December 6, 2009

Silverlight 3 and Resource File

In silverlight you can access resource file to customize label and other data that need to be localize.

1. Create class that use DataAnnotation attributes.

public class Customer
   {
       private string _name = string.Empty;
       [Display(ResourceType=typeof(SilverlightApplication2.Resourses.Strings),Name="CustomerLabel")]
       [Required(ErrorMessageResourceType = typeof(SilverlightApplication2.Resourses.Strings), ErrorMessageResourceName = "CustomerNameError")]
       public string Name
       {
           get
           {
               return _name;
           }
           set
           {
               Validator.ValidateProperty(value, new ValidationContext(this, null, null) { MemberName = "Name" });               
               _name = value;
           }
       }
   }

In above class you can see that for Display and Required attribute , ResourceType and ErrorMessageResourceType set. This will point to resource file. Also in setter of property you have to validate the value.

2. Add resource file as per your need. For example here i added Strings.Resx file.

Step 3 is very very important in order to access resource in .xap file.

3. Specially for Silverlight open Strings.Resx.cs file. Change access modifier from internal to public. Also set public for each resource string. ( See below images.)

image

image

Generate another resource file for different culture. For example fr-CA culture you need to generate Strings.fr-CA.resx.

4. Now in silverlight application if you use DataForm then just need to do following.This will automatic use label from display resource.

dfCustomer.CurrentItem = new Customer();

5. To access resource in XAML.

<UserControl xmlns:dataInput="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data.Input"  xmlns:dataFormToolkit="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data.DataForm.Toolkit"  x:Class="SilverlightApplication2.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:SilverlightApplication2.Resourses" xmlns:localCustom="clr-namespace:SilverlightApplication2"
    mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">
    <UserControl.Resources>
        <local:Strings x:Key="LocStrings"></local:Strings>
    </UserControl.Resources>
    <Grid x:Name="LayoutRoot" Background="#FF333333">     
        <StackPanel Orientation="Vertical" x:Name="MyDataForm" >
            <dataInput:ValidationSummary Height="100"></dataInput:ValidationSummary>          
            <TextBox Text="{Binding Name,Mode=TwoWay,ValidatesOnExceptions=True,NotifyOnValidationError=True}" >
            </TextBox>
            <Button Content="save" Click="Button_Click"></Button>
        </StackPanel>
    </Grid>
</UserControl>

In cs file.

public MainPage()
       {

           InitializeComponent();        
           Customer c = new Customer();
           c.Name = "TEST";
           MyDataForm.DataContext = c;
       }

 

6. Last step but very important. You have to edit .csproject file in notepad. Add supportedcultures.

<SupportedCultures>fr-CA
</SupportedCultures>

Let me know update or any other idea about resource file.

ASP.net MVC 2 : Client-side Validation and Resource file

In my previous post i gave example of client side validation. Also you need to localize error message. To do this you need to add resource file.Add resource file following way.

image

During creation of Student model you need to specify the resource.

public class Student
   {
       [Required(ErrorMessageResourceType = typeof(StudentResourse), ErrorMessageResourceName = "FirstNameError")]
       [DisplayName("User name")]
       public string FirstName { get; set; }

       [Required(ErrorMessageResourceType = typeof(StudentResourse), ErrorMessageResourceName = "EmailError")]
       [DisplayName("Email address")]
       public string Email { get; set; }

       [Required(ErrorMessageResourceType = typeof(StudentResourse), ErrorMessageResourceName = "PriceError")]       
       [DisplayName("Fees")]
       public double Fees { get; set; }
   }

Here you can see that ErrorMessageResourceType and ErrorMessageResourceName. This is used to identify resource file and resource name.

image

you need to create resource file for each culture you need. For example fr-FR.

image

As per the CurrentUICulture message is displayed.

ASP.net MVC 2 : Client-side Validation

In ASP.net MVC 2 Beta, DataAnnontation supports for validation . While creating model you can give attribute that use to support validation.

public class Student
   {
       [Required(ErrorMessage="Firstname is required field.")]
       [DisplayName("User name")]
       public string FirstName { get; set; }

      [Required(ErrorMessage = "Email is required field.")]
       [DisplayName("Email address")]

       public string Email { get; set; }

      [Required(ErrorMessage = "Fees is required field.")]      
       [DisplayName("Fees")]
       public double Fees { get; set; }
   }

Now use this model class to create view.

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MvcApplication12.Models.Student>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    ViewPage2
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script src="/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="/Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>

<h2>ViewPage2</h2>
<% Html.EnableClientValidation(); %>

    <% using (Html.BeginForm()) {%>

        <fieldset>
            <legend>Fields</legend>
            <p>
                <%= Html.LabelFor(model => model.FirstName) %>
                <%= Html.TextBoxFor(model => model.FirstName) %>
                <%= Html.ValidationMessageFor(model => model.FirstName) %>
            </p>
            <p>
                <%= Html.LabelFor(model => model.Email) %>
                <%= Html.TextBoxFor(model => model.Email) %>
                <%= Html.ValidationMessageFor(model => model.Email) %>
            </p>
            <p>
                <%= Html.LabelFor(model => model.Fees) %>
                <%= Html.TextBoxFor(model => model.Fees) %>
                <%= Html.ValidationMessageFor(model => model.Fees) %>
            </p>
            <p>
                <input type="submit" value="Create" />
            </p>
        </fieldset>

    <% } %>

    <div>
        <%=Html.ActionLink("Back to List", "Index") %>
    </div>

</asp:Content>

To enable client side validation need to add javascript and  <% Html.EnableClientValidation(); %>.

Let me know your comment on this.