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

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

Posted by: Brad Abrams on July 11, 2009

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…

image

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.   

image

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. 

image

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

image_thumb[26]

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

image_thumb[28]

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
               .Where(emp=>emp.Issues>100)
               .OrderBy(emp=>emp.EmployeeID);
}

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.. 

image_thumb[29]

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

image

   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. 

image_thumb[30]

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:

image_thumb[31]

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.. 

image_thumb[35]

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..

<riaControls:DomainDataSource.GroupDescriptors>
    <datagroup:GroupDescriptor PropertyPath="Publishers" />
</riaControls:DomainDataSource.GroupDescriptors>

image_thumb[37]

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>
</StackPanel>

and then these filter box to our DomainDataSource….

<riaControls:DomainDataSource.FilterDescriptors>
    <datagroup:FilterDescriptorCollection>
        <datagroup:FilterDescriptor PropertyPath="Origin"
                           Operator="StartsWith">
            <datagroup:ControlParameter PropertyName="Text" 
                           RefreshEventName="TextChanged"
                           ControlName="originFilterBox">
            </datagroup:ControlParameter>
        </datagroup:FilterDescriptor>
    </datagroup:FilterDescriptorCollection>
</riaControls:DomainDataSource.FilterDescriptors>

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

image_thumb[40]

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() { }
    [Key]
    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}" >
</input:AutoCompleteBox>

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;
context.Load(context.GetOriginsQuery());

Hitting F5 gives us this…

image_thumb[43]

Add To DZone
Brad Abrams

About Brad Abrams

Brad Abrams was a founding member of both the Common Language Runtime, and .NET Framework teams at Microsoft Corporation where he is currently the Group Program Manager for the UI Framework and Services team which is responsible for delivering the developer platform that spans both clients and web based applications as well as the common services that are available to all applications. Specific technologies owned by this team include ASP.NET, Atlas, and Windows Forms.

Brad has been designing parts of the .NET Framework since 1998 when he started his framework design career building the BCL (Base Class Library) that ship as a core part of the .NET Framework. Brad was also the lead editor on the Common Language Specification (CLS), the .NET Framework Design Guidelines and the libraries in the ECMA\ISO CLI Standard. Brad has been deeply involved with the WinFX and Windows Vista efforts from their beginning

Brad co-authored Programming in the .NET Environment, and was editor on .NET Framework Standard Library Annotated Reference Vol1 and Vol2 and the Framework Design Guidelines

Why Attend the NFJS Tour?

  • » Cutting-Edge Technologies
  • » Agile Practices
  • » Peer Exchange

Current Topics:

  • Languages on the JVM: Scala, Groovy, Clojure
  • Enterprise Java
  • Core Java, Java 8
  • Agility
  • Testing: Geb, Spock, Easyb
  • REST
  • NoSQL: MongoDB, Cassandra
  • Hadoop
  • Spring 4
  • Cloud
  • Automation Tools: Gradle, Git, Jenkins, Sonar
  • HTML5, CSS3, AngularJS, jQuery, Usability
  • Mobile Apps - iPhone and Android
  • More...
Learn More »