Silverlight 4.0 Tutorial (3 of N): Working with the DataForm Control
Continuing our RegistrationBooth Application, in the previous post we ended having a data grid that displays all the attendees, and a user control to add a new attendee.
The user control for adding a new attendee didn’t contain any validation logic, of course this is a bad practice, in this post we will add the necessary validation when creating adding new attendees.
- First we will need to define our validation logic for the Attendee entity, if you remember our first post when we created the Domain Service class we choose to create metadata classes for our entities, you can read more about metadata classes in the RIA services documentation (How To Add Metadata Classes).
- In the RegistrationBooth.Web project the file RegistrationDomainService.metadata.cs contains the metadata classes, we will change the AttendeeMetadata class to add some validation attributes to the different Attendee properties, you can read more about validation attributes at How To Validate Data, the final AttendeeMetadata should be as follows
- internal sealed class AttendeeMetadata
- {
- private AttendeeMetadata()
- {
- }
- [Required(ErrorMessage = "You must enter company name", AllowEmptyStrings = false)]
- [Display( Name="Company Name",Description="Name of your company")]
- public string Company { get; set; }
- public DateTime CreationDate { get; set; }
- [Required(ErrorMessage = "You must enter email", AllowEmptyStrings = false)]
- [Display( Name = "Email",Description="your Email Address")]
- [RegularExpression(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", ErrorMessage="Invalid email format")]
- public string Email { get; set; }
- [Required(ErrorMessage="You must enter first name",AllowEmptyStrings=false)]
- [Display( Name = "First Name",Description="Your First Name")]
- public string FirstName { get; set; }
- public int Id { get; set; }
- [Required(ErrorMessage = "You must enter last name", AllowEmptyStrings = false)]
- [Display( Name = "Last Name",Description="Your Last Name")]
- public string LastName { get; set; }
- public byte[] Photo { get; set; }
- public EntityCollection<SessionAttendee> SessionAttendees { get; set; }
- }
- We added RequriedAttribute for the required properties and specified the error messages that should appear if a required property is missing, the DisplayAttribute is used to provide the name (that is used as the label of the corresponding control) and the description (which appears as a ToolTip against the corresponding control), we also used a RegularExpressionAttribute for the email property to make sure that the users enter only valid email addresses.
- These metadata classes are automatically copied to the Silverlight project and compiled as part of the Silverlight application, to see this go to the RegistrationBooth project and show all the files, you will find a folder called Generated_Code, inside this folder you will find a file RegistrationBooth.Web.g.cs that contains all the classes defined on the server and shared by the client, this sharing of code allows the validation that we specified by the attributes to run directly on the client side.
- Now our entity class has the necessary metadata required for validation, let’s see how we will make use of this in creating our UI.
- We will use the DataForm control, the DataForm control can read the data annotations specified on the object class that this control is bound to.
- So to start open Home.xaml and delete the user control and the Save button, also delete the btnSave_Click method.
- From the toolbox drag and drop a DataForm control on the page, name it dfAttendee.
- Set the ItemsSource property to a binding to the element attendeeDomainDataSource and the Path is the Data property
- Because we will use the DataForm only for adding new items, we need to show only the save button, we can control what buttons (Add, Edit, Delete, Navigation, etc) should appear on the DataForm using the CommandButtonsVisibility property, so we will set this property to Commit.
- To make the DataForm open in “AddNew” mode, write the following line of code in the Page_Loaded event handler
- private void Page_Loaded(object sender, System.Windows.RoutedEventArgs e)
- {
- dataForm1.AddNewItem();
- }
- The DataForm control can automatically create a UI based on the properties of the entity that it’s bound too, but we will not use this default template because for the Photo property of the Attendee class we need to make use of the Web Cam to capture the image, so we will create a custom template for Adding Items, in the DataForm control you can specify different template for each mode so you can have a template for the view, template for the edit and a template for adding new item, in our case we need only the new item template.
- We will copy the same controls we had in the RegisterAttendee user control, we will bound the text boxes to the corresponding attendee properties, we will put each text box inside a DataField.
- The complete markup of the DataForm is shown below
- <toolkit:DataForm x:Name="dfAttendee" CommandButtonsVisibility="Commit"
- ItemsSource="{Binding ElementName=attendeeDomainDataSource, Path=Data}"
- Height="273" Width="545" >
- <toolkit:DataForm.NewItemTemplate>
- <DataTemplate>
- <Grid>
- <Grid.RowDefinitions>
- <RowDefinition Height="10*" />
- <RowDefinition Height="10*" />
- <RowDefinition Height="10*" />
- <RowDefinition Height="10*" />
- <RowDefinition Height="25*"/>
- </Grid.RowDefinitions>
- <toolkit:DataField Grid.Row="0" >
- <TextBox Height="23" HorizontalAlignment="Left" Margin="0,12,0,0" Text="{Binding FirstName,Mode=TwoWay}"
- VerticalAlignment="Top" Width="120" />
- </toolkit:DataField>
- <toolkit:DataField Grid.Row="1" >
- <TextBox Height="23" HorizontalAlignment="Left" Margin="0,12,0,0" Text="{Binding LastName,Mode=TwoWay}"
- VerticalAlignment="Top" Width="120" />
- </toolkit:DataField>
- <toolkit:DataField Grid.Row="2" >
- <TextBox Height="23" HorizontalAlignment="Left" Margin="0,12,0,0" Text="{Binding Email,Mode=TwoWay}"
- VerticalAlignment="Top" Width="120" />
- </toolkit:DataField>
- <toolkit:DataField Grid.Row="3" >
- <TextBox Height="23" HorizontalAlignment="Left" Margin="0,12,0,0" Text="{Binding Company,Mode=TwoWay}"
- VerticalAlignment="Top" Width="120" />
- </toolkit:DataField>
- <toolkit:DataField x:Name="dfPhoto" Grid.Row="4" >
- <Grid>
- <Grid.ColumnDefinitions>
- <ColumnDefinition Width="20*" />
- <ColumnDefinition Width="10*" />
- <ColumnDefinition Width="20*" />
- </Grid.ColumnDefinitions>
- <Rectangle x:Name="videoStream" Grid.Column="0" ></Rectangle>
- <ToggleButton Grid.Column="1" Height="30" Margin="0,41,0,62" Name="btnStart" Click="btnStart_Click">Start</ToggleButton>
- <Button Grid.Column="1" Height="30" Margin="0,77,0,26" Name="btnCapture" Click="btnCapture_Click">Capture</Button>
- <Image x:Name="capturedImage" Source="{Binding Path=Photo,Mode=TwoWay, Converter={StaticResource imageConverter}}" Grid.Column="2" ></Image>
- </Grid>
- </toolkit:DataField>
- </Grid>
- </DataTemplate>
- </toolkit:DataForm.NewItemTemplate>
- </toolkit:DataForm>
- if you examine the Image control at the end of the template you can see that this control is bound to the Photo property and it uses the ImageConverter class to do the conversion, we introduced the ImageConverter class in the first post and we implemented the Convert method that converts the Photo property which is a byte array to a bitmap that can be displayed in the Image control, now when we are adding a new item there will be already an image in the Image control (that we will capture using the web cam) so now we need to convert the bitmap from the Image control to a byte array that will be assigned to the Photo property, so we need to implement the second method of the Converter which is the ConvertBack method
- public object ConvertBack(object value, Type targetType, object parameter,
- System.Globalization.CultureInfo culture)
- {
- var bitmap = value as WriteableBitmap;
- var img = bitmap.ToImage();
- byte[] ba;
- var encoder = new PngEncoder();
- MemoryStream stream = new MemoryStream();
- encoder.Encode(img, stream);
- ba = stream.ToArray();
- stream.Close();
- return ba;
- }
- Now we need to write the event handlers for the two buttons (btnStart, btnCapture) which are inside the new item template, the code is shown below.
- private void btnStart_Click(object sender, RoutedEventArgs e)
- {
- ToggleButton btnStart = sender as ToggleButton;
- if (btnStart.IsChecked.Value)
- {
- StartWebcam();
- btnStart.Content = "Stop";
- }
- else
- {
- StopWebcam();
- btnStart.Content = "Start";
- }
- }
- private CaptureSource cs = null;
- private void btnCapture_Click(object sender, RoutedEventArgs e)
- {
- cs.CaptureImageAsync();
- }
- private void StartWebcam()
- {
- if (CaptureDeviceConfiguration.AllowedDeviceAccess
- CaptureDeviceConfiguration.RequestDeviceAccess())
- {
- VideoCaptureDevice vcd = CaptureDeviceConfiguration.GetDefaultVideoCaptureDevice();
- if (null != vcd)
- {
- cs = new CaptureSource();
- cs.VideoCaptureDevice = vcd;
- cs.Start();
- VideoBrush videoBrush = new VideoBrush();
- videoBrush.Stretch = Stretch.UniformToFill;
- videoBrush.SetSource(cs);
- Rectangle videoStream = dfAttendee.FindNameInContent("videoStream") as Rectangle;
- videoStream.Fill = videoBrush;
- cs.CaptureImageCompleted += new EventHandler<CaptureImageCompletedEventArgs>(cs_CaptureImageCompleted);
- }
- else
- {
- MessageBox.Show("Error initializing Webcam");
- }
- }
- }
- private void StopWebcam()
- {
- if (null != cs)
- {
- cs.Stop();
- }
- }
- void cs_CaptureImageCompleted(object sender, CaptureImageCompletedEventArgs e)
- {
- Image capturedImage = dfAttendee.FindNameInContent("capturedImage") as Image;
- capturedImage.Source = e.Result;
- }
- The code is almost identical to the code that we had inside the user control, except for the way we access the controls inside the template, for example the rectangle that displays the live stream of the web cam (videoStream) to get a reference to this rectangle we use the DataForm method FindNameInContent.
- As we mentioned previously to push the changes done locally to the server we need to call the domain data source SubmitChanges method, so whenever we click the Ok button in the DataForm we will call the SubmitChanges method to immediately submit the new attendee to the server, we can do this by adding an event handler to the DataForm EditEnded event, as shown below
- private void dfAttendee_EditEnded(object sender, DataFormEditEndedEventArgs e)
- {
- if (e.EditAction == DataFormEditAction.Commit)
- {
- attendeeDomainDataSource.SubmitChanges();
- }
- }
- Run the application and examine the labels of the controls and the tooltip that shows the description of each property.
- Try to save without entering any data to see the client side validation in action.
- The only thing missing is printing the name tag for the attendee, to do this add event handler for the domain data source SubmittedChanges event, this event is called after the SubmitChanges method is executed at the server, in this event handler we check to see if the attendee was successfully saved then we print the name tag, the code is shown below
- Attendee newAttendee;
- private void attendeeDomainDataSource_SubmittedChanges(object sender, SubmittedChangesEventArgs e)
- {
- if (e.ChangeSet.AddedEntities.Count > 0 && e.HasError ==false)
- {
- newAttendee = e.ChangeSet.AddedEntities[0] as Attendee;
- if (newAttendee != null)
- {
- PrintDocument document = new PrintDocument();
- document.PrintPage += new System.EventHandler<PrintPageEventArgs>(document_PrintPage);
- document.Print("Attendee_" + newAttendee.Id);
- }
- }
- }
- Unfortunately this code will not work, you will get Exception “Dialogs must be user-initiated” this is a Silverlight 4 built-in security measure (read more here), to resolve this issue we will change our code to show a button once the attendee is saved and we will move the printing code to this button Click event handler, the modified code is shown below
- <Button Content="Print Name Tag" Width="200"
- Click="btnPrintNameTag_Click" x:Name="btnPrintNameTag"
- Visibility="Collapsed" ></Button>
- Attendee newAttendee;
- private void attendeeDomainDataSource_SubmittedChanges(object sender, SubmittedChangesEventArgs e)
- {
- if (e.ChangeSet.AddedEntities.Count > 0 && e.HasError ==false)
- {
- newAttendee = e.ChangeSet.AddedEntities[0] as Attendee;
- if (newAttendee != null)
- {
- btnPrintNameTag.Visibility = Visibility.Visible;
- }
- }
- }
- private void btnPrintNameTag_Click(object sender, RoutedEventArgs e)
- {
- PrintDocument document = new PrintDocument();
- document.PrintPage += new System.EventHandler<PrintPageEventArgs>(document_PrintPage);
- document.Print("Attendee_" + newAttendee.Id);
- btnPrintNameTag.Visibility = Visibility.Collapsed;
- }
That’s all for this post, next time we will continue :).
You can download the code from here.
Comments