Business Apps Example for Silverlight 3 RTM and .NET RIA Services July Update: Part 2: Rich Data Query

Continuing in our discussion of Silverlight 3 and  the brand new update to .NET RIA Services and the update the example from my Mix09 talk “building business applications with Silverlight 3”.

You can watch the original  video of the full session 

The demo requires (all 100% free and always free):

  1. VS2008 SP1 (Which includes Sql Express 2008)
  2. Silverlight 3 RTM
  3. .NET RIA Services July '09 Preview

Also, download the full demo files and check out the running application.

Today, we will talk about Rich Data Query. 


Rich Data Query

Next up, let’s talk about data query.  Nearly every business application deals with data.   Let’s look at how to do this with .NET RIA Services.   We will start out in the web project.   For this example I will use an Entity Framework data model, but RIA Services works great with any form of data from plain olld CLR objects to an xml file, to web services to Linq to Sql.   For starters, let’s build an Entity Framework model for our data.   For this walk through, we will start simply…


I updated the pluralization of the entity name

Now, how are we going to access this data from the SL client?  Well, traditionally many business applications have started out as 2-tier apps. That has a number of problems around scaling and flexibility… and more to the point it just doesn’t work with the Silverlight\web client architecture.   


So developers are thrust into the n-tier world.  .NET RIA Services make it very easy to create scalable, flexible n-tier services that builds on WCF and ADO.NET Data Services. 


These .NET RIA Services model your UI-tier application logic and encapsulate your access to varies data sources from traditional relational data to POCO (plain old CLR objects) to cloud services such as Azure, S3, etc via REST, etc.  One of the great thing about this is that you can move from an on premises Sql Server to an Azure hosted data services without having to change any of your UI logic. 

Let’s look at how easy it is to create these .NET RIA Services. 

Right click on the server project and select the new Domain Service class


In the wizard, select your data source.  Notice here we could have chosen to use a Linq2Sql class, a POCO class, etc, etc. 


In the SuperEmployeeDomainService.cs class we have stubs for all the CRUD method for accessing your data.   You of course should go in and customize these for your domain.  For the next few steps we are going to use GetSuperEmployees(), so I have customized it a bit. 

 public IQueryable<SuperEmployee> GetSuperEmployees()
     return this.Context.SuperEmployeeSet

Now, let’s switch the client side.  Be sure to build the solution so you can access it from the client directly.  These project are linked because we selected the “ASP.NET enable” in the new project wizard. 

Drag the DataGrid off the toolbox… notice this works with any control.. 


In HomePage.Xaml add

 <data:DataGrid x:Name="dataGrid1" Height="500"></data:DataGrid> 

And in the code behind add MyApp.Web… notice this is interesting as MyApp.Web is defined on the server…  you can now access the client proxy for the server DomainServices locally


    1: var context = new SuperEmployeeDomainContext();
    2: dataGrid1.ItemsSource = context.SuperEmployees;
    3: context.Load(context.GetSuperEmployeesQuery());

In line 1, we create our SuperEmployeesDomainContext.. this is the client side of the SuperEmployeesDomainService.  Notice the naming convention here…

In line 2, we are databinding the grid to the SuperEmployees.. then in line 3 we are loading the SuperEmployees, that class the GetSuperEmployees() method we defined on the server.  Notice this is all async of course, but we didn’t have to deal with the complexities of the async world. 


The result!  We get all our entries back, but in the web world,don’t we want to do paging and server side sorting and filtering?  Let’s look at how to do that.

First, remove the code we just added to codebehind.

Then, to replace that, let’s add a DomainDataSource. You can just drag it in from the toolbox:


Then edit it slightly to get:

    1: <riaControls:DomainDataSource x:Name="dds" 
    2:         AutoLoad="True"
    3:         QueryName="GetSuperEmployeesQuery"
    4:         LoadSize="20">
    5:     <riaControls:DomainDataSource.DomainContext>
    6:         <App:SuperEmployeeDomainContext/>
    7:     </riaControls:DomainDataSource.DomainContext>
    8: </riaControls:DomainDataSource>

Notice in line 3, we are calling that GetSuperEmployeesQuery method from the DomainContext specified in line 6.  

In line 4, notice we are setting the LoadSize to 20.. that means we are going to download data in batches of 20 at a time.

Now, let’s bind it to a the DataGrid and show a little progress indicator (that you can get in the sample).. 

    1: <activity:Activity IsActive="{Binding IsBusy, ElementName=dds}"
    2:                    VerticalAlignment="Top" 
    3:                    HorizontalAlignment="Left" 
    4:                    Width="900" Margin="10,5,10,0">
    5:     <StackPanel>
    6:         <data:DataGrid x:Name="dataGrid1" Height="300" Width="900"
    7:                        ItemsSource="{Binding Data, ElementName=dds}">
    8:          </data:DataGrid>
    9:          <data:DataPager PageSize="10" Width="900"
   10:                          HorizontalAlignment="Left"
   11:                          Source="{Binding Data, ElementName=dds}" 
   12:                          Margin="0,0.2,0,0" />
   13:      </StackPanel>
   14: </activity:Activity>

In line 6, there is a datagrid, that is bound  to the DDS.Data property (in line 7).  Then we add a DataPager in line 9, that is bound to the same datasource.  this gives us the paging UI.  Notice in line 9 we are setting the display to 10 records at a time.  Finally we wrap the whole thing in an ActivityControl to show progress.

The cool thing is that the ActivityControl, the DataGrid and the DataPager can all be used with any datasource such as data from WCF service, REST service, etc. 

Hit F5, and you see.. 


Notice we are loading 20 records at a time, but showing only 10.  So advancing one page is client only, but advancing again we get back to the server and load the next 20.  Notice this all works well with sorting as well.   And the cool thing is where is the code to handle all of this?  Did i write in on the server or the client?  neither.  Just with the magic of linq, things compose nicely and it i just falls out. 

I can early add grouping..

     <datagroup:GroupDescriptor PropertyPath="Publishers" />


Let’s add filtering… First add a label and a textbox..

 <StackPanel Orientation="Horizontal" Margin="0,0,0,10">
     <TextBlock Text="Origin: "></TextBlock>
     <TextBox x:Name="originFilterBox" Width="75" Height="20"></TextBox>

and then these filter box to our DomainDataSource….

         <datagroup:FilterDescriptor PropertyPath="Origin"
             <datagroup:ControlParameter PropertyName="Text" 

When we hit F5, we get a filter box, and as we type in it we do a server side filtering of the results. 


Now, suppose we wanted to make that a autocomplete box rather an a simple text box.   The first thing we’d have to do is get all the options.  Notice we have to get those from the server (the client might not have them all because we are doing paging, etc).  To do this we add a method to our DomainService. 

 public class Origin
     public Origin() { }
     public string Name { get; set; }
     public int Count { get; set; }

and the method that returns the Origins…

 public IQueryable<Origin> GetOrigins()
     var q = (from emp in Context.SuperEmployeeSet
              select emp.Origin).Distinct()
             .Select(name => new Origin
                 Name = name,
                 Count = Context.SuperEmployeeSet.Count
                     (emp => emp.Origin.Trim() == name.Trim())
     q = q.Where(emp => emp.Name != null);
     return q;

Now we need to add the autocomplete control from the Silverlight 3 SDK.  Replace the textbox with this:

 <input:AutoCompleteBox  x:Name="originFilterBox" Width="75" Height="30"
                         ValueMemberBinding="{Binding Name}" 
                         ItemTemplate="{StaticResource OriginsDataTemplate}" >

Then we just need to add a little bit of code behind to load it up.

 var context = dds.DomainContext as SuperEmployeeDomainContext;
 originFilterBox.ItemsSource = context.Origins;

Hitting F5 gives us this…


Validating Data Update

Now – that was certainly some rich ways to view data, but business apps need to update data as well.  Let’s look at how to do that.   First replace all the xaml below the DDS with this… it gives us a nice master-details view.

    1: <StackPanel  Style="{StaticResource DetailsStackPanelStyle}">
    3:                    <activity:Activity IsActive="{Binding IsBusy, ElementName=dds}">
    4:                        <StackPanel>
    5:                            <StackPanel Orientation="Horizontal" Margin="0,0,0,10">
    6:                                <TextBlock Text="Origin: " />
    8:                                <input:AutoCompleteBox  x:Name="originFilterBox" Width="338" Height="30"
    9:                                                    ValueMemberBinding="{Binding Name}" 
   10:                                                    ItemTemplate="{StaticResource OriginsDataTemplate}" />
   11:                            </StackPanel>
   13:                            <data:DataGrid x:Name="dataGrid1" Height="380" Width="380" 
   14:                                           IsReadOnly="True" AutoGenerateColumns="False" 
   15:                                           HorizontalAlignment="Left" 
   16:                                           HorizontalScrollBarVisibility="Disabled"
   17:                                           ItemsSource="{Binding Data, ElementName=dds}" 
   18:                                       >
   19:                                <data:DataGrid.Columns>
   20:                                    <data:DataGridTextColumn Header="Name" Binding="{Binding Name}" />
   21:                                    <data:DataGridTextColumn Header="Employee ID"  Binding="{Binding EmployeeID}" />
   22:                                    <data:DataGridTextColumn Header="Origin"  Binding="{Binding Origin}" />
   23:                                </data:DataGrid.Columns>
   24:                            </data:DataGrid>
   26:                            <data:DataPager PageSize="13" Width="379" 
   27:                                            HorizontalAlignment="Left"
   28:                                            Source="{Binding Data, ElementName=dds}" 
   29:                                            Margin="0,0.2,0,0" />
   31:                            <StackPanel Orientation="Horizontal" Margin="0,5,0,0">
   32:                                <Button Content="Submit" Width="105" Height="28"
   33:                                    />
   36:                                <!--new emp button here-->
   39:                            </StackPanel>
   41:                        </StackPanel>
   42:                    </activity:Activity>
   44:                    <StackPanel Margin="35,0,0,0" HorizontalAlignment="Left" VerticalAlignment="Top" Height="498" >
   45:                        <dataControls:DataForm x:Name="dataForm1" Height="393" Width="331"
   46:                               VerticalAlignment="Top"       
   47:                               Header="Product Details"
   48:                               CurrentItem="{Binding SelectedItem, ElementName=dataGrid1}" 
   49:                                HorizontalAlignment="Left" >
   50:                            <dataControls:DataForm.EditTemplate>
   51:                                <DataTemplate>
   52:                                    <StackPanel>
   53:                                        <dataControls:DataField>
   54:                                            <TextBox Text="{Binding Name, Mode=TwoWay}" />
   55:                                        </dataControls:DataField>
   56:                                        <dataControls:DataField>
   57:                                            <TextBox Text="{Binding EmployeeID, Mode=TwoWay}" />
   58:                                        </dataControls:DataField>
   59:                                        <dataControls:DataField>
   60:                                            <TextBox Text="{Binding Origin, Mode=TwoWay}" />
   61:                                        </dataControls:DataField>
   62:                                        <dataControls:DataField>
   63:                                            <TextBox Text="{Binding Sites, Mode=TwoWay}" />
   64:                                        </dataControls:DataField>
   66:                                        <dataControls:DataField>
   67:                                            <TextBox Text="{Binding Gender, Mode=TwoWay}" />
   68:                                        </dataControls:DataField>
   70:                                        <dataControls:DataField>
   71:                                            <TextBox Text="{Binding Publishers, Mode=TwoWay}" />
   72:                                        </dataControls:DataField>
   73:                                        <dataControls:DataField>
   74:                                            <controls:DatePicker Text="{Binding LastEdit, Mode=OneWay}"></controls:DatePicker>
   75:                                        </dataControls:DataField>
   76:                                        <dataControls:DataField>
   77:                                            <TextBox Text="{Binding Issues, Mode=TwoWay}" />
   78:                                        </dataControls:DataField>
   79:                                    </StackPanel>
   80:                                </DataTemplate>
   81:                            </dataControls:DataForm.EditTemplate>
   84:                        </dataControls:DataForm>
   88:                        <!--Permalink here-->
   90:                    </StackPanel>
   93:                </StackPanel>

Through line 35, this is pretty much the same as what we had. 

Then in line 38, we add a DataForm control that gives us some nice way to view and edit a particular entity. 

Hit F5


This looks like the traditional master-details scenario.


Notice as we change items they are marked as “Dirty” meaning they need to be submitted back to the server.  You can make edits to many items, unmake some edits and the dirty marker goes away. 

Now we need to wire up the submit button. 

    1: private void SubmitButton_Click(object sender, RoutedEventArgs e)
    2: {
    3:     dataForm1.CommitEdit();
    4:     dds.SubmitChanges();
    5: }

We first need to commit the item we are currently editing, then we just submit changes.  This batches up the diffs and sends them back the server.  and our Update method is called.  Notice the dirty bit goes away.

Now, that is cool, but what about Data Validation?  Well, “for free” you get type level validation (if the filed is typed as an int you and you enter a string you get an error). 


Now let’s see if we can add a bit more.  We do that by editing the SuperEmployeeDomainService.metadata.cs on the server.  It is important to do it on the server so that the system does all the validations are done once for a great UX experience and then again on the server for data integrity.  By the time your Update method is called on your DomainService you can be sure that all the validations have been done. 

Here are some of the validations we can apply.. 

 public int EmployeeID;
 public EntityState EntityState;
     ErrorMessage = "Gender must be 'Male' or 'Female'")]
 public string Gender;
 [Range(0, 10000,
     ErrorMessage = "Issues must be between 0 and 1000")]
 public Nullable<int> Issues;
 public Nullable<DateTime> LastEdit;
 public string Name;

Just rebuilding and running the app gives us great validation in the UI and in the middle tier. 


Notice how I can navigate between the errors and input focus moves to the next one. 

That was updating data, what about adding new data?

To do that, let’s explorer the new Silverlight 3 ChildWindow.

Right click on Views and add new Item Child Window


Let’s wire it up to show the default window. First add a button to the main form to display the childwindow we just created.

 <Button Content="Add New" 
         Width="105" Height="28"
         Margin="5,0,0,0" HorizontalAlignment="Left"
         Click="AddNew_Click" ></Button>

Then wire it up..

 private void AddNew_Click(object sender, RoutedEventArgs e)
     var w = new AddNewWindow();


Notice it already has a OK and Cancel buttons and a close box that work great right out of the box.  We just need to add a DataForm.  Because we are bound to the same model, the DataForm will pick up all the same features as the update one we just looked at.

 <dataControls:DataForm x:Name="newEmployeeForm" Height="393" Width="331"
                        Header="Add New Super Employee"
                         HorizontalAlignment="Left" >
                     <TextBox Text="{Binding Name, Mode=TwoWay}" />
                     <TextBox Text="{Binding EmployeeID, Mode=TwoWay}" />
                     <TextBox Text="{Binding Origin, Mode=TwoWay}" />
                     <TextBox Text="{Binding Sites, Mode=TwoWay}" />
                     <TextBox Text="{Binding Gender, Mode=TwoWay}" />
                     <TextBox Text="{Binding Publishers, Mode=TwoWay}" />
                     <controls:DatePicker Text="{Binding LastEdit, Mode=OneWay}"></controls:DatePicker>
                     <TextBox Text="{Binding Issues, Mode=TwoWay}" />

Now, in code behind we need to write this up by adding a class level field..

 public SuperEmployee NewEmployee { get; set; }

..initializing the instance in the constructor

             NewEmployee = new SuperEmployee();
             NewEmployee.LastEdit = DateTime.Now.Date;
             this.newEmployeeForm.CurrentItem = NewEmployee;

..handling the OK button

 private void OKButton_Click(object sender, RoutedEventArgs e)
     this.DialogResult = true;


Great… now let’s commit this change locally.

 void addNewWindow_Closed(object sender, EventArgs e)
     var win = sender as AddNewWindow;
     var context = dds.DomainContext as SuperEmployeeDomainContext;
     if (win.DialogResult == true)

From this, the Submit button will send this change to the server.