PDC09 Talk: Building Amazing Business Applications with Silverlight 4, RIA Services and Visual Studio 2010
I had a great time at my talk today at PDC2009. I was able to spend much of the time in a demo… Here is a summary of that demo so you can walk through it on your own machine:
What you need to get started:
- Visual Studio 2010 Beta2
- Silverlight 4 Beta (now includes RIA Services)
- Completed Solution (starting step and demo files)
- Check out the slides
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…
- using System.Linq;
- using System.Web.Ria;
- using System.Web.DomainServices.Providers;
- namespace MyApp.Web
- {
- [EnableClientAccess]
- public class DishViewDomainService :
- LinqToEntitiesDomainService<DishViewEntities>
- {
- public IQueryable<Restaurant> GetRestaurants()
- {
- return this.ObjectContext.Restaurants
- .Where (r=>r.City != "Raleigh")
- .OrderBy(r=>r.ID);
- }
- }
- }
In line 7 – 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 8: 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 9: 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 11: 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.
- <Grid x:Name="LayoutRoot">
- <data:DataGrid AutoGenerateColumns="True"
- Name="dataGrid1"
- Height="456"
- Width="618" />
- </Grid>
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..
- var context = new DishViewDomainContext();
- 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"
- LoadedData="restaurantDomainDataSource_LoadedData"
- Name="restaurantDomainDataSource"
- QueryName="GetRestaurantsQuery"
- Width="0"
- Margin="320,240,320,144">
- <riaControls:DomainDataSource.DomainContext>
- <my:DishViewDomainContext />
- </riaControls:DomainDataSource.DomainContext>
- </riaControls:DomainDataSource>
If you notice the LoadedData event is wired up… This is to give a nice user experience in the case of an error. You should certainly customize what is defaulted for you… but it is a good place to start.
- private void restaurantDomainDataSource_LoadedData(object sender,
- LoadedDataEventArgs e)
- {
- if (e.HasError)
- {
- MessageBox.Show(e.Error.ToString(), "Load Error",
- MessageBoxButton.OK);
- e.MarkErrorAsHandled();
- }
- }
Finally, the DataGrid is created with a set of columns.
- <data:DataGrid AutoGenerateColumns="False"
- ItemsSource="{Binding ElementName=restaurantDomainDataSource, Path=Data}"
- Name="restaurantDataGrid"
- RowDetailsVisibilityMode="VisibleWhenSelected">
- <data:DataGrid.Columns>
- <data:DataGridTemplateColumn x:Name="imagePathColumn"
- Header="Image Path"
- Width="SizeToHeader">
- <data:DataGridTemplateColumn.CellTemplate>
- <DataTemplate>
- <Image Source="{Binding Path=ImagePath}" />
- </DataTemplate>
- </data:DataGridTemplateColumn.CellTemplate>
- </data:DataGridTemplateColumn>
- <data:DataGridTextColumn x:Name="nameColumn"
- Binding="{Binding Path=Name}"
- Header="Name"
- Width="SizeToHeader" />
- <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"
- 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="78"
- HorizontalAlignment="Left"
- Margin="226,201,0,0"
- Name="busyIndicator1"
- VerticalAlignment="Top"
- Width="177"
- 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 : IValueConverter
- {
- public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
- {
- string path = value.ToString();
- path = path.Replace(":", "");
- path = path.Replace("/", "");
- path = path.Replace("\\", "");
- if (path.Length > 100)
- path = path.Substring(0, 100)
- return "https://localhost/Images/" + path
- }
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>
- <my1:ImagePathConverter x:Key="ImagePathConverter1" />
- </navigation:Page.Resources>
and
- <data:DataGridTemplateColumn.CellTemplate>
- <DataTemplate>
- <Image Source="{Binding Path=ImagePath, Converter={StaticResource ImagePathConverter1}}" />
- </DataTemplate>
- </data:DataGridTemplateColumn.CellTemplate>
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 void Button_Click(object sender, System.Windows.RoutedEventArgs e)
- {
- var res = this.restaurantDomainDataSource.DataView.CurrentItem
- as Restaurant;
- NavigationService.Navigate(new Uri("/Plates?restaurantId="
- + res.ID, UriKind.Relative));
- }
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 IQueryable<Plate> GetPlates()
- {
- return this.ObjectContext.Plates
- .OrderBy(p => p.Name);
- }
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 IQueryable<Plate> GetPlates(int resId)
- {
- return this.ObjectContext.Plates
- .Where (p=>p.RestaurantID == resId)
- .OrderBy(p => p.Name);
- }
Now, back on the client, we just need to pass the query string param…
- protected override void OnNavigatedTo(NavigationEventArgs e)
- {
- plateDomainDataSource.QueryParameters.Add(
- new System.Windows.Data.Parameter()
- {
- ParameterName = "resId",
- Value = NavigationContext.QueryString["restaurantId"]
- });
- }
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 void UpdatePlate(Plate currentPlate)
- {
- currentPlate.NumberUpdates++;
- var orginal = this.ChangeSet.GetOriginal(currentPlate);
- if (orginal.Price != currentPlate.Price)
- {
- currentPlate.Price += 1; // add 1 dollar fee for changing price
- }
- this.ObjectContext
- .AttachAsModified(currentPlate, orginal);
- }
In line 3, 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 5, we pull out the original value.. .this is the plate instance as the client saw it before it was updated.
In line 7-10, 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 12-13, we submit this change to the database.
Now we just need to drop a button on the form.
Then write some codebehind..
- private void button1_Click(object sender, RoutedEventArgs e)
- {
- this.plateDomainDataSource.SubmitChanges();
- }
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 string Name;
- public Nullable<int> NumberUpdates;
- [Range(0, 999)]
- public Nullable<decimal> Price;
- [RegularExpression(@"^http\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(/\S*)?$",
- ErrorMessage = "Please use standard Url format")]
- public string Uri;
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 static ValidationResult IsDescriptionValid(string description)
- {
- if (description != null && description.Split().Length < 5)
- {
- var vr = new ValidationResult("Valid descriptions must have 5 or more words.");
- return vr;
- }
- return ValidationResult.Success;
- }
Then to wire this up to the description property…
- [CustomValidation(typeof(MyApp.Web.PlateValidationRules),
- "IsDescriptionValid")]
- public string Description;
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.
- [EnableClientAccess]
- [RequiresAuthentication]
- public class DishViewDomainService :
- LinqToEntitiesDomainService<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.
- public partial class User : UserBase
- {
- public string FriendlyName { get; set; }
- public string BackgroundColor { get; set; }
- }
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 void button1_Click(object sender, System.Windows.RoutedEventArgs e)
- {
- var context = WebContext.Current.Authentication;
- this.userDomainDataSource.SubmitChanges();
- userDomainDataSource.SubmittedChanges += (s, ev) =>
- {
- if (!context.IsBusy) context.LoadUser();
- };
- }
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!