I had a great time at my talk  PDC2009 talk, but i was disappointed that I could not demo in both C# and VB… So here is the next best thing: A full play-by-play of the demo, but all in VB!   Enjoy.

What you need to get started:

Starting Off

I am starting off with the new Business Application Template that gets installed with RIA Services. 

image

This new template includes:

    • Pattern for page navigation
    • Log\Logout and new user registration support
    • Localizable
    • User settings
    • Shared Code

For this demo, I am going to used a customized version of the template..

After you create the project, you see we have a simple solution setup that follows the “RIA Application” pattern.  That is one application that happens to span a client (Silverlight) and server (asp.net) tiers.  These two are tied such that any change in the Silverlight client is reflected in the server project (a new XAP is placed in client bin) and appropriate changes in the server result in new functionality being exposed to the Silverlight client. To parts of the same application.

image

Exposing the Data

I started out with an Entity Framework model.  RIA Services supports any DAL including Linq2Sql, NHibernate as well as DataSets and DataReader\Writer.   But EF has made some great improvements in .NET 4, so I felt it was a good place to start. 

So here is the EF model I created.  Basically we have a set of restaurants, each of which has a set of plates they serve.  A very simple model designed many to show off the concepts.  

image

Then we need to place to write our business logic that controls how the Silverlight client can interact with this data.    To do this create a new DomainService.  

image

Then select the tables you want to expose:

image

Now, let’s look at our code for the DomainService…

  1. Imports MyApp.VB
  2. Imports System
  3. Imports System.Data
  4. Imports System.Linq
  5. Imports System.Web.DomainServices
  6. Imports System.Web.Ria
  7. Imports System.Web.DomainServices.Providers
  8.  
  9.  
  10. <EnableClientAccess()> _
  11. Public Class PlateViewDomainService
  12.     Inherits LinqToEntitiesDomainService(Of DishViewEntities)
  13.  
  14.     Public Function GetRestaurants() As IQueryable(Of Restaurant)
  15.         Return From r In ObjectContext.Restaurants
  16.                Where r.City <> "Raligh"
  17.                Order By r.ID
  18.     End Function
  19.  
  20.  
  21. End Class
  22.  
  23.  

In line 10 – we are enabling this service to be accessed from clients.. without this, the DomainService is only accessible from on the machine (for example for an ASP.NET hosted on the same machine).

In line 11: we are defining the DomainService – you should think of a DomainService as just a special kind of WCF Service.. one that is higher level and has all the right defaults set so that there is zero configuration needed.   Of course the good news is that if you *need* to you can get access to the full richness of WCF and configure the services however you’d like.

In line 12: you see we are using the LinqToEntitiesDomainService.  RIA Services supports any DAL including LinqToSql or NHibernate.  Or what I think is very common is just POCO.. that is deriving from DomainService directly.  See examples of these here��

In line 14:  We are defining a Query method.. this is based on LINQ support added in VS2008.  Here we define the business logic involved in return data to the client.  When the framework calls this method, it will compose a LINQ query including paging, sorting, filtering from the client then execute it directly against the EF model which translate it into optimized TSQL code.  So no big chunks of unused data are brought to the mid-tier or the client. 

Consuming the data on the client

Now let’s switch over the client project and look at how we consume this. 

in Views\Home.xaml we have a very simple page with just a DataGrid defined.

  1. <data:DataGrid AutoGenerateColumns="True"
  2.                Name="dataGrid1"
  3.                Height="456"
  4.                Width="618" />
  5.  

now let’s flip over to codebhind..

Notice we have a MyApp.Web namespace available on the client. Notice that is the same namespace we defined our DomainService in..

image

So, let’s create a local context for accessing our DomainService.  First thing you will notice is that VS2010 Intellisense makes it very easy to find what we want.. it now matches on any part of the class name..  So just typing “domainc” narrows our options to the right one.. 

image

 

  1. Dim context = New PlateViewDomainContext()
  2. dataGrid1.ItemsSource = context.Restaurants
  3.  
  4. context.Load(context.GetRestaurantsQuery())
  5.  

In line 2, notice there is a property on context called Restaurants.  How did we get that there?  Well, there is a query method defined on the DomainService returning a type of type Restaurant.  This gives us a very clean way to do databinding.  Notice this call is actually happening async, but we don’t have to deal with any of that complexity.  No event handlers, callbacks, etc. 

In line 4, while the whole point of RIA Services is to make n-tier development as easy as two-tier development that most of us are used to, we want to make sure the applications that are created are well behaved.   So part of this is we want to be explicit when a network call is being made.. this is not transparent remoting.  Network calls must be explicit.    In this line we are mentioning which query method to use as you might define more than one for the same type with different logic. 

Now we run it..

image

This is very cool and simple.  But in a real world case, i am guessing you have more than 20 records… sometimes you might have 100s, or thousands or more.  You can’t just send all those back to the client.  Let’s see how you can implement paging and look at some of the new design time features in VS2010 as well. 

RIA Services support in Visual Studio 2010

Let’s delete that code we just wrote and flip over to the design surface and delete that datagrid. 

Drop down the DataSources window (you may need to look under the Data menu for “Show Data Sources”

image

If you are familiar with WinForms or WPF development, this will look at least somewhat familiar to you.   Notice our DishViewDomainContext is listed there with a table called Restaurant.  Notice this is exactly what we saw in the code above because this window is driven off that same DomainContext. 

Dropping down the options on Restaurant, we see we have a number of options for different controls that can be used to view this data… of course this is extensible and we expect 3rd party as well as your custom controls to work here.    Next see the query method here that is checked.  That lists all the available options for query methods that return Restaurant.

image

Now if we expand the view on Restaurant, we see all the data member we have exposed.  This view gives us a chance to change how each data member will be rendered.  Notice I have turned off the ID and changed the Imagepath to an Image control.  Again this is an extensible and we expect 3rd party controls to plug in here nicely. 

image

Now, drag and drop Restaurant onto the form and we get some UI

image

And for you Xaml heads that want to know what really happens… Two things.  First if the DomainDataSource is not already created, one is created for you.

  1. <riaControls:DomainDataSource AutoLoad="True"
  2.                               Height="0"
  3.                               Name="RestaurantDomainDataSource"
  4.                               QueryName="GetRestaurantsQuery"
  5.                               Width="0">
  6.     <riaControls:DomainDataSource.DomainContext>
  7.         <my:PlateViewDomainContext />
  8.     </riaControls:DomainDataSource.DomainContext>
  9. </riaControls:DomainDataSource>
  10.  

 

Finally, the DataGrid is created with a set of columns. 

  1. <data:DataGrid AutoGenerateColumns="False"
  2.                Height="200"
  3.                HorizontalAlignment="Left"
  4.                ItemsSource="{Binding ElementName=RestaurantDomainDataSource, Path=Data}"
  5.                Margin="190,110,0,0"
  6.                Name="RestaurantDataGrid"
  7.                RowDetailsVisibilityMode="VisibleWhenSelected"
  8.                VerticalAlignment="Top"
  9.                Width="400">
  10.     <data:DataGrid.Columns>
  11.         <data:DataGridTextColumn x:Name="AddressColumn"
  12.                                  Binding="{Binding Path=Address}"
  13.                                  Header="Address"
  14.                                  Width="SizeToHeader" />
  15.  

Then setup a grid cell by click 4/5ths of the way down on the left grid adorner.  Then select the grid, right click, select reset layout all. 

image

.. add poof! VS automatically lays out the DataGrid to fill the cell just right. 

image

Now, personally, I always like the Name column to come first.  Let’s go fix that by using the DataGrid column designer.  Right click on the DataGrid select properties then click on the Columns property..

image

In this designer you can control the order of columns and the layout, etc.   I moved the image and name fields to the top.

Now, let’s add a DataPager such that we only download a manageable number of records at a time. From the toolbox, simply drag the datapager out.

image

We use our same trick to have VS auto layout the control  Right click on it and select Reset Layout\All. 

image

That is cool, but there is a big  gap between the DataGrid and the DataPager.. I really want them to be right.  This is easy to fix.  Right click on the grid adorner and select “Auto”..

image

Perfect!

image

Now, we just need to wire this up to the same DataSource our DataGrid is using “connect-the-dots” databinding.  Simply drag the Restaurant from the DataSources window on top of the DataGrid. 

image

For you Xaml heads, you’ll be interested in the Xaml this creates..

  1. <data:DataPager Grid.Row="1"
  2.                 Name="DataPager1"
  3.                 PageSize="10"
  4.                 Source="{Binding ElementName=RestaurantDomainDataSource, Path=Data}" />
  5.  

Notice, we don’t need to create a new DomainDataSource here… we will use the one that is already on the page.

Now, we are doing an async call.. so let’s drag a  BusyIndicator from the new Silverlight 4 Toolkit.

image

We need to write up the IsBusy to the restaurantDomainDataSource.DomainContext.IsLoading… Luckily there is some nice databinding  helper in VS2010.  Select properties, then IsBusy, then DataBinding.

image

Again, for you Xaml heads, the Xaml that gets generated is pretty much what you’d expect.

  1. <controlsToolkit:BusyIndicator Height="83"
  2.                                HorizontalAlignment="Left"
  3.                                Margin="274,137,0,0"
  4.                                Name="BusyIndicator1"
  5.                                VerticalAlignment="Top"
  6.                                Width="188"
  7.                                IsBusy="{Binding ElementName=RestaurantDomainDataSource, Path=DomainContext.IsLoading}" />
  8.  

Loading…

image

and once it is loaded…

image

Very cool…  that was a very easy was to get your data.    Page through it and notice that with each page we are going back all the way to the data tier to load more data.  So you could just as easily do this on a dataset of million+ records.    But what is more, is that sorting works as well and just as you’d expect.  It doesn’t sort just the local data, it sorts the full dataset and it does it all way back onto the data tier and just pulls forward the page of data you need to display.

But our pictures are not showing up… let’s look at how we wire up the pictures.  The reason they are not showing up is that our database returns just the simple name of the image, not the full path.  This allows us to be flexible about the where the images are stored.   The standard way to handle this is to write a value converter.     Here is a simple example:

  1. Public Class ImagePathConverter
  2.     Implements IValueConverter
  3.  
  4.     Function Convert(ByVal value As Object, ByVal targetType As Type, ByVal parameter As Object, ByVal culture As Globalization.CultureInfo) As Object _
  5.         Implements IValueConverter.Convert
  6.  
  7.         Dim path As String
  8.         path = value.ToString()
  9.         path = path.Replace(":", "")
  10.         path = path.Replace("/", "")
  11.         path = path.Replace("\\", "")
  12.         If path.Length > 100 Then
  13.             path = path.Substring(0, 100)
  14.         End If
  15.         Return "http://hanselman.com/abrams/Images/Plates/" + path
  16.  
  17.     End Function
  18.  

 

Now, let’s look at how we wire this converter to the UI.   First, let’s use the Document Outline to drill through the visual tree to find the Image control. 

image

Then we select the properties on the image and wire up this converter.  If you have done this in Xaml directly before, you know it is hard to get right.  VS2010 makes this very easy!

image

Oh, and for you Xaml heads… here is what VS created..

  1. <navigation:Page.Resources>
  2.     <my:ImagePathConverter x:Key="ImagePathConverter1" />
  3. </navigation:Page.Resources>
  4.  

and

  1. <data:DataGridTemplateColumn x:Name="ImagePathColumn"
  2.                              Header="Image Path"
  3.                              Width="SizeToHeader">
  4.     <data:DataGridTemplateColumn.CellTemplate>
  5.         <DataTemplate>
  6.             <Image Source="{Binding Path=ImagePath, Converter={StaticResource ImagePathConverter1}}" />
  7.         </DataTemplate>
  8.     </data:DataGridTemplateColumn.CellTemplate>
  9. </data:DataGridTemplateColumn>
  10.  

Silverlight Navigation

Now let’s look at how we drill down and get the details associated with each of these records.  I want to show this is a “web” way… So I’ll show how to create a deep link to a new page that will list just the plates for the restaurant you select. 

First we add a bit of Xaml to add the link to the datagrid..

  1. <data:DataGrid.Columns>
  2.         <data:DataGridTemplateColumn Header="">
  3.             <data:DataGridTemplateColumn.CellTemplate>
  4.                 <DataTemplate>
  5.                     <Button Content="+"
  6.                             Style="{StaticResource DetailsButtonStyle}"
  7.                             Click="Button_Click"></Button>
  8.                 </DataTemplate>
  9.             </data:DataGridTemplateColumn.CellTemplate>
  10.         </data:DataGridTemplateColumn>
  11.  

And to implement the button click handler…

  1. Private Sub Button_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
  2.  
  3.     Dim res As Restaurant
  4.     res = RestaurantDomainDataSource.DataView.CurrentItem
  5.  
  6.     NavigationService.Navigate(New Uri("/Plates?restaurantId=" _
  7.      & res.ID, UriKind.Relative))
  8. End Sub

Here we are getting the currently selected Restaurant, then we cons up a new URL to the page “Plates”.  We pass a query string parameter of restaurantId…

Now, let’s build out the Plates page that will the list of Plates for this restaurant.  First let’s great a a Plates page.  Let’s add a new Plates under the Views directory. 

image

Now we need to define a query to return the Plates.  Notice that only the data you select is exposed.  So we get to go back to the server, to our DishViewDomainService and add a new query method.

  1. Public Function GetPlates() As IQueryable(Of Plate)
  2.     Return From r In ObjectContext.Plates
  3.            Order By r.ID
  4. End Function

Now we go back to the client, and see your DataSources window now offers a new datasource: Plates.

image

Now, just as we saw above, I will drag and drop that data source onto the form and i get a nice datagrid alreayd wired up to a DomainDataSource. 

image

Then, with a little formatting exactly as we saw above, we end up with…

image

And when we run it… First, you see the link we added to the list of Restaurants..

image

Clicking on anyone of them navigates us to our Plates page we just built. 

image

Customized Data Access

This is cool, but notice we are actually returning *all* the plates, not just the plates from the restaurant selected.    To address this first we need modify our GetPlates() query method to take in a resource id. 

  1. Public Function GetPlates(ByVal resId As Integer) As IQueryable(Of Plate)
  2.     Return From r In ObjectContext.Plates
  3.            Where r.RestaurantID = resId
  4.            Order By r.ID
  5. End Function
  6.  

 

Now, back on the client, we just need to pass the query string param… 

  1. Protected Overrides Sub OnNavigatedTo(ByVal e As System.Windows.Navigation.NavigationEventArgs)
  2.     Dim param = New Parameter()
  3.     param.ParameterName = "resId"
  4.     param.Value = NavigationContext.QueryString("restaurantId")
  5.  
  6.     PlateDomainDataSource.QueryParameters.Add(param)
  7.  
  8. End Sub
  9.  

Now, we run it and we get the just the plates for the restaurant we selected.

image

what’s more is we now have a deep link such that it works when I email, IM or tweet this link to my buddy who happens to run a different browser ;-)

image

Ok… now for a details view…  Let’s do a bit more layout in the Plates.xaml.   First, let’s split the form in half vertically to give us some cells to work in. 

image

In the bottom left we will put the details view to allow us to edit this plate data.  Let’s go back to the DataSources window and change the UI type to Details. 

image

Dragging that Details onto the form… we get some great UI generation that we can go in and customize.

image

In particular, let’s format that Price textbox as a “currency”… using the new String Formatting support in Silverlight 4. 

image

And again, for you Xaml heads… this created:

  1. Text="{Binding Path=Price, Mode=TwoWay, ValidatesOnExceptions=true, NotifyOnValidationError=true, StringFormat=\{0:c\}}"

Now, let’s add an image to the other side.  Simply drop an Image control on the form and select Reset Layout\All

image

Now we can easily change the image to be “Uniform”

image

Now we need to write up the binding here so that as selection changes, this image is update.  Luckily, that is very easy to do.    Simply drag and drop from the Data Sources window…

image

Then we need to wire up our converter just as we saw before..

image

Run it…

image

That looks great! 

But when we try edit something, we get this error..

image

Editing Data

Ahh, that is a good point, we need to go back and explicitly define a Update method to our DomainService on the server.

  1. Public Sub UpdatePlate(ByVal currentPlate As Plate)
  2.     currentPlate.NumberUpdates += 1
  3.     Dim orginal = ChangeSet.GetOriginal(currentPlate)
  4.     If orginal.Price <> currentPlate.Price Then
  5.         ' add 1 dollar fee for changing price
  6.         currentPlate.Price += 1
  7.     End If
  8.     ObjectContext() _
  9.         .AttachAsModified(currentPlate, orginal)
  10. End Sub

In line 2, notice we take the NumberUpdates and increment by one.  it is nice that we send the entry entity back and forth, so we can do entity level operations very easily.   

Next in line 3, we pull out the original value.. .this is the plate instance as the client saw it before it was updated. 

In line 4-7, we first check to see if the price has changed, if it has, we add a fee of one dollar for a price change. 

Finally  in line 8-9, we submit this change to the database. 

Now we just need to drop a button on the form.

image

Then write some codebehind..

  1. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles Button1.Click
  2.     PlateDomainDataSource.SubmitChanges()
  3. End Sub
  4.  

What this is going to do is find all the entities that are dirty (that have changes) and package them up and send them to the server. 

Now notice if you make a change price to the data and hit submit the NumberUpdates goes up by one and the the price has the one dollar fee added.

image

Then submit..  NumberUpdates is now 63 and the price is $73.84..

image

Then if you set a breakpoint on the server, change two or three records on the client.  Notice the breakpoint gets hit for each change.    We are batching these changes to make an efficient communication pattern. 

image

Great.. now let’s look at data validation.

We get some validation for free.  for example Calorie Count is a int, if we put a string in, we get a stock error message. 

image

If we want to customize this a bit more, we can go back to the server and specify our validation there.  It is important to do it on the server because you want validation to happen  on the client for good UI, but on the server for the tightest security.  Following the DRY principle (Don’t Repeat Yourself) we have a single place to put this validation data that works on the client and the server.

  1. <Required(ErrorMessage:="Please provide a name")>
  2. Public Name As String
  3.  
  4. Public NumberUpdates As Nullable(Of Integer)
  5.  
  6. <Range(0, 99)>
  7. Public Price As Nullable(Of Decimal)
  8.  
  9. <RegularExpression("^http\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(/\S*)?$",
  10.         ErrorMessage:="Please use standard Url format")>
  11. Public Uri As String
  12.  

 

The data validation attributes are a core part of .NET with ASP.NET Dynamic Data and ASP.NET MVC using the exact same model.

But what if they are not expressive enough for you?  For example, say I have a custom validation I have for making sure the description is valid..   To do that, I can write some .NET code that executes on the server AND the client.  Let’s see how to do that.  First I create a class on the server..

image

Notice the name here PlateValidationRules.shared.cs…. the “.shared” part is important… it is what tells us that this code is meant to be on the client and the server.

In this case, i am saying a valid description is one that has 5 more more words

  1. Public Class PlateValidationRules
  2.     Public Shared Function IsDescriptionValid(ByVal description As String) As ValidationResult
  3.         If (description <> Nothing And description.Split().Length < 5) Then
  4.             Dim vr = New ValidationResult("Valid descriptions must have 5 or more words.")
  5.             Return vr
  6.         End If
  7.         Return ValidationResult.Success
  8.     End Function
  9. End Class

Then to wire this up to the description property…

  1. <CustomValidation(GetType(PlateValidationRules),
  2.             "IsDescriptionValid")>
  3. Public Description As String
  4.  

Then running the app, we see all our validations…

image

Personalization and Authentication

Lots of times in business applications we are dealing with valuable data that we need to make sure the user is authentication before we return in.  Luckily this is very easy to do with RIA Services.  Let’s go back to our DomainServices on the server and add the RequiresAuthentication attribute. 

  1. <RequiresAuthentication()>
  2. <EnableClientAccess()>
  3. Public Class PlateViewDomainService
  4.     Inherits LinqToEntitiesDomainService(Of DishViewEntities)
  5.  

Then when you run the application..

image

So let’s log in…  I don’t have an account created yet, luckily the Business Application Template supports new user registration.  All this is based on ASP.NET Authentication system that has been around sense ASP.NET 2.0. 

Here we are creating a new user…

image

And now we get our data…

image

Now, that we have a user concept.. why don’t we add one more setting to let the user customize this page.    So we edit the web.config file to add a BackgroundColor. 

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <configuration>
  3.   <system.web>
  4.     <profile>
  5.       <properties>
  6.         <add name="FriendlyName" />
  7.         <add name="BackgroundColor"/>
  8.       </properties>
  9.     </profile>
  10.  

And we go into the User.cs class on the server and add our BackgroundColor. 

  1. Partial Public Class User
  2.     Inherits UserBase
  3.     
  4.     Private _FriendlyName As String
  5.     Private _BackgroundColor As String
  6.  
  7.     Public Property FriendlyName() As String
  8.         Get
  9.             Return _FriendlyName
  10.         End Get
  11.         Set(ByVal value As String)
  12.             _FriendlyName = value
  13.         End Set
  14.     End Property
  15.  
  16.     Public Property BackgroundColor() As String
  17.         Get
  18.             Return _BackgroundColor
  19.         End Get
  20.         Set(ByVal value As String)
  21.             _BackgroundColor = value
  22.         End Set
  23.     End Property
  24.  
  25.  

Now, back on the client, let’s build out UI using the DataSources window just as we have seen above.  But this time, I have created a very simple ColorPicker control in order to show that it is possible to use your own custom control. 

image

Drag and drop that onto the form..

image

Then change the binding to be TwoWay using the databinding picker. 

image

Then I think we need a nice header here with the User name in it.  To so that, let’s add a TextBlock, set the fontsize to be big.   Then do connect the dots databinding to write up to the user name. 

image

Then let’s use the string format databinding to customize this a bit..

image

Next we put a Submit button. 

  1. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles Button1.Click
  2.     Dim context = WebContext.Current.Authentication
  3.  
  4.     UserDomainDataSource.SubmitChanges()
  5.     AddHandler UserDomainDataSource.SubmittedChanges, AddressOf SubmittedChanges
  6.  
  7. End Sub
  8. Private Sub SubmittedChanges(ByVal sender As Object, ByVal e As SubmittedChangesEventArgs)
  9.     Dim context = WebContext.Current.Authentication
  10.     If Not context.IsBusy Then
  11.         context.LoadUser()
  12.     End If
  13. End Sub

Now when we run it… we can modify the user settings. 

image

The really cool part is that if the user goes to another machine and logs in, they get the exact same experience. 

image

Summary

Wow, we have seen a lot here.. We walked through end-to-end how to build a Business Application in Silverlight with .NET RIA Services.  We saw the query support, validating update, authorization and personalization as well as all the great new support in VS2010.    Enjoy!