Monday, December 10, 2012

Validation of create user form in Silverlight

Validation of create user form in Silverlight

I am making a Silverlight 4.0 Navigation Application with Authentication Service to manage users, log in/out and so forth.

I have used the msdn tutorial on this page: http://msdn.microsoft.com/en-us/library/ee942451%28v=vs.91%29.aspx

It works great. I can create users with some custom profile properties and log in and out.

The problem is my create user form. As in the tutorial I have in my service project made a class called NewUser, with data annotations. These seems to work, as if I try to create a user with a invalid field, the creation fails, and i get an exception, with the message that there are validation errors.

I would like this validation to work with my form. In other forms I just bind an instance of a class to the form and set the binding for each field with validationOnException to true and notifyOnValidationError to true.

I have made the bindings in the create user form as in my other forms, but they do not seem to work. I have tried to set a breakpoint in a set of a property on the NewUser class. It looks like it do not get called/used at all.

This is most likely a simple matter of me missing something, but I can not found out what. Does it have anything to do with the fact that the NewUser class is in my service project and the form is in the client project. I hope you guys can help me.

My code for the NewUser class

public class NewUser  {      private string username;      [Key]     [Required()]     public string UserName { get; set; }      [Key]     [Required()]     [RegularExpression(@"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$", ErrorMessage="Invalid email. An email must use the format username@mycompany.com")]     public string Email { get; set; }       [Required()]     public string Firstname { get; set; }      [Required()]     public string Lastname { get; set; }      [Required()]     public DateTime Birthsday { get; set; }      [Required()]     public bool SentNewsletter { get; set; }      [Required()]     public bool SentReminders { get; set; }        [Required()]     public string Password { get; set; }      [CustomValidation(typeof(RegistrationValidator), "IsPasswordConfirmed")]             public string ConfirmPassword { get; set; }      [Required()]     public string SecurityQuestion { get; set; }      [Required()]     public string SecurityAnswer { get; set; }  } 

My create user form xaml

<navigation:Page x:Class="OenskePortalen.Views.Pages.CreateNewUser"         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"        mc:Ignorable="d"        xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"        xmlns:input="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data.Input"                         xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"        xmlns:uc="clr-namespace:OenskePortalen.Views.Controls"        d:DesignWidth="640" d:DesignHeight="680"        Title="CreateNewUser Page"> <Grid x:Name="LayoutRoot" Background="White">     <Grid.RowDefinitions>         <RowDefinition Height="50" />         <RowDefinition Height="40"/>         <RowDefinition Height="40"/>         <RowDefinition Height="40"/>         <RowDefinition Height="40"/>         <RowDefinition Height="40"/>         <RowDefinition Height="40"/>         <RowDefinition Height="40"/>         <RowDefinition Height="40"/>         <RowDefinition Height="40"/>         <RowDefinition Height="40"/>         <RowDefinition Height="40"/>         <RowDefinition Height="40"/>         <RowDefinition Height="*"/>     </Grid.RowDefinitions>     <Grid.ColumnDefinitions>         <ColumnDefinition Width="180"/>         <ColumnDefinition Width="10"/>         <ColumnDefinition Width="160"/>         <ColumnDefinition Width="*"/>     </Grid.ColumnDefinitions>      <uc:InfoBox Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="4" DisplayText="Her kan du oprette dig som bruger på ØnskePortalen" VerticalAlignment="Top"/>      <TextBlock Grid.Row="1" Grid.Column="0" Text="Brugernavn" VerticalAlignment="Center"/>     <TextBlock Grid.Row="1" Grid.Column="1" Text=":" VerticalAlignment="Center"/>     <TextBox Grid.Row="1" Grid.Column="2" x:Name="txtUsername" Text="{Binding UserName, Mode=TwoWay, ValidatesOnExceptions=True, NotifyOnValidationError=True}" VerticalAlignment="Center" Width="150" Margin="5"  HorizontalAlignment="Left"  />      <TextBlock Grid.Row="2" Grid.Column="0" Text="Fornavn" VerticalAlignment="Center"/>     <TextBlock Grid.Row="2" Grid.Column="1" Text=":" VerticalAlignment="Center"/>     <TextBox Grid.Row="2" Grid.Column="2" x:Name="txtFirstname" Text="{Binding Firstname, Mode=TwoWay, ValidatesOnExceptions=True, NotifyOnValidationError=True}" VerticalAlignment="Center" Width="150" Margin="5" HorizontalAlignment="Left"  />      <TextBlock Grid.Row="3" Grid.Column="0" Text="Efternavn" VerticalAlignment="Center"/>     <TextBlock Grid.Row="3" Grid.Column="1" Text=":" VerticalAlignment="Center"/>     <TextBox Grid.Row="3" Grid.Column="2" x:Name="txtLastname"  Text="{Binding Lastname, Mode=TwoWay, ValidatesOnExceptions=True, NotifyOnValidationError=True}" VerticalAlignment="Center" Width="150" Margin="5" HorizontalAlignment="Left" />      <TextBlock Grid.Row="4" Grid.Column="0" Text="Email" VerticalAlignment="Center"/>     <TextBlock Grid.Row="4" Grid.Column="1" Text=":" VerticalAlignment="Center"/>     <TextBox Grid.Row="4" Grid.Column="2" x:Name="txtEmail" Text="{Binding Email, Mode=TwoWay, ValidatesOnExceptions=True, NotifyOnValidationError=True}" VerticalAlignment="Center" Width="150" Margin="5" HorizontalAlignment="Left" />      <TextBlock Grid.Row="5" Grid.Column="0" Text="Adgangskode" VerticalAlignment="Center"/>     <TextBlock Grid.Row="5" Grid.Column="1" Text=":" VerticalAlignment="Center"/>     <PasswordBox Grid.Row="5" Grid.Column="2" x:Name="txtPassword" Password="{Binding Password, Mode=TwoWay, ValidatesOnExceptions=True, NotifyOnValidationError=True}" VerticalAlignment="Center" Width="150" Margin="5" />      <TextBlock Grid.Row="6" Grid.Column="0" Text="Gentag adgangskode" VerticalAlignment="Center"/>     <TextBlock Grid.Row="6" Grid.Column="1" Text=":" VerticalAlignment="Center"/>     <PasswordBox Grid.Row="6" Grid.Column="2" x:Name="txtPasswordRepeat" Password="{Binding PasswordConfirm, Mode=TwoWay, ValidatesOnExceptions=True, NotifyOnValidationError=True}" VerticalAlignment="Center" Width="150" Margin="5" />      <TextBlock Grid.Row="7" Grid.Column="0" Text="Sikkerhedsspørgsmål" VerticalAlignment="Center"/>     <TextBlock Grid.Row="7" Grid.Column="1" Text=":" VerticalAlignment="Center"/>     <TextBox Grid.Row="7" Grid.Column="2" x:Name="txtPasswordQuestion" Text="{Binding SecurityQuestion, Mode=TwoWay, ValidatesOnExceptions=True, NotifyOnValidationError=True}" VerticalAlignment="Center" Width="150" Margin="5" HorizontalAlignment="Left" />      <TextBlock Grid.Row="8" Grid.Column="0" Text="Sikkerhedssvar" VerticalAlignment="Center"/>     <TextBlock Grid.Row="8" Grid.Column="1" Text=":" VerticalAlignment="Center"/>     <TextBox Grid.Row="8" Grid.Column="2" x:Name="txtPasswordAnswer" Text="{Binding SecurityAnswer, Mode=TwoWay, ValidatesOnExceptions=True, NotifyOnValidationError=True}" VerticalAlignment="Center" Width="150" Margin="5" HorizontalAlignment="Left" />      <TextBlock Grid.Row="9" Grid.Column="0" Text="Fødselsdag" VerticalAlignment="Center"/>     <TextBlock Grid.Row="9" Grid.Column="1" Text=":" VerticalAlignment="Center"/>     <sdk:DatePicker Grid.Row="9" Grid.Column="2" x:Name="dpBirthsday" SelectedDate="{Binding Birthsday, Mode=TwoWay, ValidatesOnExceptions=True, NotifyOnValidationError=True}"  VerticalAlignment="Center" Width="150" Margin="5" HorizontalAlignment="Left"/>      <TextBlock Grid.Row="10" Grid.Column="0" Text="Nyhedsbrev" VerticalAlignment="Center"/>     <TextBlock Grid.Row="10" Grid.Column="1" Text=":" VerticalAlignment="Center"/>     <CheckBox Grid.Row="10" Grid.Column="2" x:Name="cboxNewsletter" IsChecked="{Binding SentNewsletter, Mode=TwoWay, ValidatesOnExceptions=True, NotifyOnValidationError=True}" VerticalAlignment="Center" Margin="5"/>      <TextBlock Grid.Row="11" Grid.Column="0" Text="Påmindelser om fødselsdage" VerticalAlignment="Center"/>     <TextBlock Grid.Row="11" Grid.Column="1" Text=":" VerticalAlignment="Center" />     <CheckBox Grid.Row="11" Grid.Column="2" x:Name="cboxReminders" IsChecked="{Binding SentReminders, Mode=TwoWay, ValidatesOnExceptions=True, NotifyOnValidationError=True}" VerticalAlignment="Center" Margin="5"/>        <StackPanel Grid.Row="12" Grid.Column="0" Grid.ColumnSpan="3" HorizontalAlignment="Right" Orientation="Horizontal" >          <Button x:Name="btnCreate" Style="{StaticResource GreenButton}" Background="{StaticResource GreenGradientBrush}" Height="20" Margin="5" Click="btnCreate_Click" Cursor="Hand" >             <TextBlock Text="Opret ny bruger" Style="{StaticResource textStyleBlack}" />         </Button>          <Button x:Name="btnCancel" Style="{StaticResource BlueButton}" Background="{StaticResource BlueGradientBrush}" Height="20" Margin="5"  Click="btnCancel_Click" Cursor="Hand" >             <TextBlock Text="Annuller" Style="{StaticResource textStyleBlack}" />         </Button>     </StackPanel>      <input:ValidationSummary Grid.Row="13" Grid.Column="0" Grid.ColumnSpan="3" />  </Grid> 

And my create user form code behind

public partial class CreateNewUser : Page {     private NewUser user;      public CreateNewUser()     {         InitializeComponent();         user = new NewUser();         LayoutRoot.DataContext = user;         dpBirthsday.SelectedDate = DateTime.Now;         cboxNewsletter.IsChecked = true;         cboxReminders.IsChecked = true;     }      private void btnCreate_Click(object sender, RoutedEventArgs e)     {         updateValidation();          if (!Validation.GetHasError(LayoutRoot))         {              RegistrationDomainContext context = new RegistrationDomainContext();             NewUser user = new NewUser();             try             {                 user.UserName = txtUsername.Text;                 user.Password = txtPassword.Password;                 user.Email = txtEmail.Text;                 user.ConfirmPassword = txtPassword.Password;                 user.SecurityQuestion = txtPasswordQuestion.Text;                 user.SecurityAnswer = txtPasswordAnswer.Text;                 user.Firstname = txtFirstname.Text;                 user.Lastname = txtLastname.Text;                 user.Birthsday = dpBirthsday.SelectedDate.GetValueOrDefault(DateTime.Now);                 user.SentNewsletter = cboxNewsletter.IsChecked.GetValueOrDefault(true);                 user.SentReminders = cboxReminders.IsChecked.GetValueOrDefault(true);                  context.NewUsers.Add(user);                 context.SubmitChanges(RegisterUser_Completed, null);             }             catch (Exception exc)             {                 ErrorWindow w = new ErrorWindow(exc);                 w.Show();             }           } // end validation       }       private void RegisterUser_Completed(SubmitOperation so)     {         if (so.HasError)         {              ErrorWindow ew = new ErrorWindow(so.Error);             ew.Show();             so.MarkErrorAsHandled();         }         else         {             LoginParameters lp = new LoginParameters(txtUsername.Text, txtPassword.Password);         }     }       private void btnCancel_Click(object sender, RoutedEventArgs e)     {         MainPage mp = Application.Current.RootVisual as MainPage;         mp.contentFrame.Navigate(new Uri("/home", UriKind.Relative));     }       private void updateValidation()     {         foreach (var current in LayoutRoot.Children)         {             if (current is TextBox)                 (current as TextBox).GetBindingExpression(TextBox.TextProperty).UpdateSource();              if (current is PasswordBox)                 (current as PasswordBox).GetBindingExpression(PasswordBox.PasswordProperty).UpdateSource();         }     } } 

Answers & Comments...

Answer: 1

I believe that you can't databind to a private field - try changing user in your code-behind to a public property (and maybe look at implementing INotifyPropertyChanged).

by : Alycehttp://stackoverflow.com/users/1516678




No comments:

Post a Comment

Send us your comment related to the topic mentioned on the blog