PDC09 Talk: Building Amazing Business Applications with Silverlight 4, RIA Services and Visual Studio 2010 – Now in Visual Basic!!
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:
- Visual Studio 2010 Beta2
- Silverlight 4 Beta (now includes RIA Services)
- Completed Solution (in VB)
- Check out the slides and video from the talk
Starting Off
I am starting off with the new Business Application Template that gets installed with RIA Services.
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.
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.
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.
Then select the tables you want to expose:
Now, let’s look at our code for the DomainService…
- Imports MyApp.VB
- Imports System
- Imports System.Data
- Imports System.Linq
- Imports System.Web.DomainServices
- Imports System.Web.Ria
- Imports System.Web.DomainServices.Providers
- <EnableClientAccess()> _
- Public Class PlateViewDomainService
- Inherits LinqToEntitiesDomainService(Of DishViewEntities)
- Public Function GetRestaurants() As IQueryable(Of Restaurant)
- Return From r In ObjectContext.Restaurants
- Where r.City <> "Raligh"
- Order By r.ID
- End Function
- End Class
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.
- <data:DataGrid AutoGenerateColumns="True"
- Name="dataGrid1"
- Height="456"
- Width="618" />
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..
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..
- Dim context = New PlateViewDomainContext()
- dataGrid1.ItemsSource = context.Restaurants
- context.Load(context.GetRestaurantsQuery())
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..
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”
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.
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.
Now, drag and drop Restaurant onto the form and we get some UI
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.
- <riaControls:DomainDataSource AutoLoad="True"
- Height="0"
- Name="RestaurantDomainDataSource"
- QueryName="GetRestaurantsQuery"
- Width="0">
- <riaControls:DomainDataSource.DomainContext>
- <my:PlateViewDomainContext />
- </riaControls:DomainDataSource.DomainContext>
- </riaControls:DomainDataSource>
Finally, the DataGrid is created with a set of columns.
- <data:DataGrid AutoGenerateColumns="False"
- Height="200"
- HorizontalAlignment="Left"
- ItemsSource="{Binding ElementName=RestaurantDomainDataSource, Path=Data}"
- Margin="190,110,0,0"
- Name="RestaurantDataGrid"
- RowDetailsVisibilityMode="VisibleWhenSelected"
- VerticalAlignment="Top"
- Width="400">
- <data:DataGrid.Columns>
- <data:DataGridTextColumn x:Name="AddressColumn"
- Binding="{Binding Path=Address}"
- Header="Address"
- Width="SizeToHeader" />
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.
.. add poof! VS automatically lays out the DataGrid to fill the cell just right.
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..
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.
We use our same trick to have VS auto layout the control Right click on it and select Reset Layout\All.
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”..
Perfect!
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.
For you Xaml heads, you’ll be interested in the Xaml this creates..
- <data:DataPager Grid.Row="1"
- Name="DataPager1"
- PageSize="10"
- Source="{Binding ElementName=RestaurantDomainDataSource, Path=Data}" />
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.
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.
Again, for you Xaml heads, the Xaml that gets generated is pretty much what you’d expect.
- <controlsToolkit:BusyIndicator Height="83"
- HorizontalAlignment="Left"
- Margin="274,137,0,0"
- Name="BusyIndicator1"
- VerticalAlignment="Top"
- Width="188"
- IsBusy="{Binding ElementName=RestaurantDomainDataSource, Path=DomainContext.IsLoading}" />
Loading…
and once it is loaded…
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:
- Public Class ImagePathConverter
- Implements IValueConverter
- Function Convert(ByVal value As Object, ByVal targetType As Type, ByVal parameter As Object, ByVal culture As Globalization.CultureInfo) As Object _
- Implements IValueConverter.Convert
- Dim path As String
- path = value.ToString()
- path = path.Replace(":", "")
- path = path.Replace("/", "")
- path = path.Replace("\\", "")
- If path.Length > 100 Then
- path = path.Substring(0, 100)
- End If
- Return "https://hanselman.com/abrams/Images/Plates/" + path
- End Function
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.
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!
Oh, and for you Xaml heads… here is what VS created..
- <navigation:Page.Resources>
- <my:ImagePathConverter x:Key="ImagePathConverter1" />
- </navigation:Page.Resources>
and
- <data:DataGridTemplateColumn x:Name="ImagePathColumn"
- Header="Image Path"
- Width="SizeToHeader">
- <data:DataGridTemplateColumn.CellTemplate>
- <DataTemplate>
- <Image Source="{Binding Path=ImagePath, Converter={StaticResource ImagePathConverter1}}" />
- </DataTemplate>
- </data:DataGridTemplateColumn.CellTemplate>
- </data:DataGridTemplateColumn>
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..
- <data:DataGrid.Columns>
- <data:DataGridTemplateColumn Header="">
- <data:DataGridTemplateColumn.CellTemplate>
- <DataTemplate>
- <Button Content="+"
- Style="{StaticResource DetailsButtonStyle}"
- Click="Button_Click"></Button>
- </DataTemplate>
- </data:DataGridTemplateColumn.CellTemplate>
- </data:DataGridTemplateColumn>
And to implement the button click handler…
- Private Sub Button_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
- Dim res As Restaurant
- res = RestaurantDomainDataSource.DataView.CurrentItem
- NavigationService.Navigate(New Uri("/Plates?restaurantId=" _
- & res.ID, UriKind.Relative))
- 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.
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.
- Public Function GetPlates() As IQueryable(Of Plate)
- Return From r In ObjectContext.Plates
- Order By r.ID
- End Function
Now we go back to the client, and see your DataSources window now offers a new datasource: Plates.
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.
Then, with a little formatting exactly as we saw above, we end up with…
And when we run it… First, you see the link we added to the list of Restaurants..
Clicking on anyone of them navigates us to our Plates page we just built.
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.
- Public Function GetPlates(ByVal resId As Integer) As IQueryable(Of Plate)
- Return From r In ObjectContext.Plates
- Where r.RestaurantID = resId
- Order By r.ID
- End Function
Now, back on the client, we just need to pass the query string param…
- Protected Overrides Sub OnNavigatedTo(ByVal e As System.Windows.Navigation.NavigationEventArgs)
- Dim param = New Parameter()
- param.ParameterName = "resId"
- param.Value = NavigationContext.QueryString("restaurantId")
- PlateDomainDataSource.QueryParameters.Add(param)
- End Sub
Now, we run it and we get the just the plates for the restaurant we selected.
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 ;-)
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.
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.
Dragging that Details onto the form… we get some great UI generation that we can go in and customize.
In particular, let’s format that Price textbox as a “currency”… using the new String Formatting support in Silverlight 4.
And again, for you Xaml heads… this created:
- 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
Now we can easily change the image to be “Uniform”
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…
Then we need to wire up our converter just as we saw before..
Run it…
That looks great!
But when we try edit something, we get this error..
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.
- Public Sub UpdatePlate(ByVal currentPlate As Plate)
- currentPlate.NumberUpdates += 1
- Dim orginal = ChangeSet.GetOriginal(currentPlate)
- If orginal.Price <> currentPlate.Price Then
- ' add 1 dollar fee for changing price
- currentPlate.Price += 1
- End If
- ObjectContext() _
- .AttachAsModified(currentPlate, orginal)
- 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.
Then write some codebehind..
- Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles Button1.Click
- PlateDomainDataSource.SubmitChanges()
- End Sub
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.
Then submit.. NumberUpdates is now 63 and the price is $73.84..
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.
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.
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.
- <Required(ErrorMessage:="Please provide a name")>
- Public Name As String
- Public NumberUpdates As Nullable(Of Integer)
- <Range(0, 99)>
- Public Price As Nullable(Of Decimal)
- <RegularExpression("^http\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(/\S*)?$",
- ErrorMessage:="Please use standard Url format")>
- Public Uri As String
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..
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
- Public Class PlateValidationRules
- Public Shared Function IsDescriptionValid(ByVal description As String) As ValidationResult
- If (description <> Nothing And description.Split().Length < 5) Then
- Dim vr = New ValidationResult("Valid descriptions must have 5 or more words.")
- Return vr
- End If
- Return ValidationResult.Success
- End Function
- End Class
Then to wire this up to the description property…
- <CustomValidation(GetType(PlateValidationRules),
- "IsDescriptionValid")>
- Public Description As String
Then running the app, we see all our validations…
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.
- <RequiresAuthentication()>
- <EnableClientAccess()>
- Public Class PlateViewDomainService
- Inherits LinqToEntitiesDomainService(Of DishViewEntities)
Then when you run the application..
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…
And now we get our data…
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.
- <?xml version="1.0" encoding="utf-8"?>
- <configuration>
- <system.web>
- <profile>
- <properties>
- <add name="FriendlyName" />
- <add name="BackgroundColor"/>
- </properties>
- </profile>
And we go into the User.cs class on the server and add our BackgroundColor.
- Partial Public Class User
- Inherits UserBase
- Private _FriendlyName As String
- Private _BackgroundColor As String
- Public Property FriendlyName() As String
- Get
- Return _FriendlyName
- End Get
- Set(ByVal value As String)
- _FriendlyName = value
- End Set
- End Property
- Public Property BackgroundColor() As String
- Get
- Return _BackgroundColor
- End Get
- Set(ByVal value As String)
- _BackgroundColor = value
- End Set
- End Property
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.
Drag and drop that onto the form..
Then change the binding to be TwoWay using the databinding picker.
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.
Then let’s use the string format databinding to customize this a bit..
Next we put a Submit button.
- Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles Button1.Click
- Dim context = WebContext.Current.Authentication
- UserDomainDataSource.SubmitChanges()
- AddHandler UserDomainDataSource.SubmittedChanges, AddressOf SubmittedChanges
- End Sub
- Private Sub SubmittedChanges(ByVal sender As Object, ByVal e As SubmittedChangesEventArgs)
- Dim context = WebContext.Current.Authentication
- If Not context.IsBusy Then
- context.LoadUser()
- End If
- End Sub
Now when we run it… we can modify the user settings.
The really cool part is that if the user goes to another machine and logs in, they get the exact same experience.
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!
Comments
Anonymous
November 29, 2009
It is too bad not a single demo I saw at PDC was in VB. Seems like Microsoft is forgetting the language that got them where they are today.Anonymous
November 30, 2009
The comment has been removedAnonymous
November 30, 2009
The comment has been removedAnonymous
December 03, 2009
The comment has been removedAnonymous
December 30, 2009
Any pointer or updates to my or Nick posts. We are trying to make a decision, any help is very very much appreciated. thank you Happy New year to all.Anonymous
December 31, 2009
The comment has been removedAnonymous
January 11, 2010
Hi Brad, Thanx for doing this in VB too - makes me feel like I'm not the only one developing SL in VB.. ;) I've downloaded the app, but when running it i get the following error "System.Windows.Ria.DomainOperationException: Load operation failed for query" (GetRestaurant) Any idea why? - I guess its something with access to the mdf file but I've given my sql service account (Network service) and everything access to it so..? Any help greatly appreciated!Anonymous
January 17, 2010
Hi Brad, Thanx for your example. But I have some problems 1- My database is Oracle how can I connect with it. 2- I have 150 tables at my hr can you give me a method for dynamic binding Ex: one or two classes for many forms (it is better for maintenance). 3- I need a method for modal dialog that return one or more value to the parent form. 4- What about reports? That is my problems to transfer my business application. Thanx againAnonymous
January 21, 2010
I get the same error with this vb version of the project. "System.Windows.Ria.DomainOperationException: Load operation failed for query 'GetRestaurant'. Access denied to DomainOperationEntry 'GetRestaurants'. Th c# project does not have this issue. Both projects complain that a Type 'DemoControls.ColorPicker' is not defined, and related msgs. At least this project runs (search does not work). This kind of stuff is hard for newbs to debug; hopefully someone who knows more can help with a solution.