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]

publicclassDishViewDomainService :

LinqToEntitiesDomainService<DishViewEntities>

{

publicIQueryable<Restaurant> GetRestaurants()

{

returnthis.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 = newDishViewDomainContext();

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.

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.

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:

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.

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.

publicIQueryable<Plate> GetPlates()

{

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

publicIQueryable<Plate> GetPlates(int resId)

{

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

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

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.

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

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

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

publicclassPlateValidationRules

{

publicstaticValidationResult IsDescriptionValid(string description)

{

if (description != null && description.Split().Length < 5)

{

var vr = newValidationResult(“Valid descriptions must have 5 or more words.”);

return vr;

}

returnValidationResult.Success;

}

Then to wire this up to the description property…

[CustomValidation(typeof(MyApp.Web.PlateValidationRules),

“IsDescriptionValid”)]

publicstring 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]

publicclassDishViewDomainService :

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.

<?xmlversion=“1.0“encoding=“utf-8“?>

<configuration>

<system.web>

<profile>

<properties>

<addname=“FriendlyName“ />

<addname=“BackgroundColor“/>

</properties>

</profile>

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

publicpartialclassUser : UserBase

{

publicstring FriendlyName { get; set; }

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

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!

Error 1 The type or namespace name ‘UserRegistrationContext’ could not be found (are you missing a using directive or an assembly reference?) C:UsersJohnDownloadsMyAppSL4MyAppMyAppViewsLoginRegistrationForm.xaml.cs 22 17 MyApp

You guys are moving too fast for industry. Before the strategist can figure out version 1.0, 2.0 is released and now 4.0 after 3.0. This definitely hurts as those top non-technical people always thinks to wait until Microsoft comes with better version tomorrow.

I like Silverlight but just has concern with this continuous new releases.

I noticed something that I thought was odd. When working in VS2008 and Blend on the same project at the same time and if you change something in the code in blend and save it and when you switch to VS, Visual Studio would prompt you that the file has changed and do you want to reload it (Yes, YesAll, No, Cancel).

Well now you were ONLY in VS2010 and all the changes were being made in VS and not blend, so why was VS10 prompting that question several times during your demo?

Is the new version of WCF RIA Silverlight Business Application template intended to be used only with DataContract? Or can it also be used in a reasonable straightforward configurable manner with other serializers such as XmlSerializer ? If not, how much hacking away at WCF RIA would be necessary to get it to work with XmlSerializer?

Would it be possible that you explain this same thing to us with adding new records and not only updating the ones than currently exists? Also how do we call stored procedures with RIA services? Thanks Mr. Brad 🙂

When adding a new project using the Silverlight (4) Business Application Template to an existing solution in Visual Studio 2010 Beta 2, I don’t get asked if I want to host the Silverlight app in an existing web site in the solution. I do get prompted if I use the Silverlight Application or Silverlight Navigation Application templates. This would seem to complicate things a bit if I want to ultimately host the app through Azure.

I tried to turn Imagepath to an Image control, but the only choices, I had are: TextBlock, TextBox, and combobox, what do I need to do to be able to image the image control in the dropdown of the imagepath.

if this question has no thing to do with silverlight, please direct me to the right direction.

from a freshly installed vs2010 beta 2, using vista ultimate sqlserver 2005 express I get this;

The database ‘C:USERS….DESKTOPRIASERVICEMYAPP.STARTERMYAPP.WEBAPP_DATADISHVIEW.MDF’ cannot be opened because it is version 655. This server supports version 612 and earlier. A downgrade path is not supported.

Could not open new database ‘C:USERSHENRIKDESKTOPRIASERVICEMYAPP.STARTERMYAPP.WEBAPP_DATADISHVIEW.MDF’. CREATE DATABASE is aborted.

An attempt to attach an auto-named database for file C:UsersHenrikDesktopRiaServiceMyApp.StarterMyApp.WebApp_DataDishView.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share

I repeated the same steps that you did but the Data Sources window is empty. All code is generated fine as I can use the DomainService from code behind, but the Data Source pane doesn’t populate. I’m using the Visual Stuidio 2010 Professional Edition Beta 2.

Excellent video for beginners to RIA service. I tried to deploy this demo on IIS ,but error messages always occur when I submit changes. The error detail is :

at System.Windows.Ria.OperationBase.InvokeCompleteAction()

at System.Windows.Ria.OperationBase.Complete(Exception error)

at System.Windows.Ria.SubmitOperation.Complete(OperationErrorStatus errorStatus)

at System.Windows.Ria.DomainContext.<>c__DisplayClassb.<SubmitChanges>b__3(Object )

Caused by: And error occurred while submitting changes on the DomainContext of type ‘DishViewDomainContext’ and the error was not handled. You must handle the SubmittedChanges event on the DomainDataSource and call SubmittedChangesEventArgs.MarkErrorAsHandled() to avoid this exception.

at System.Windows.Ria.OperationBase.InvokeCompleteAction()

at System.Windows.Ria.OperationBase.Complete(Exception error)

at System.Windows.Ria.SubmitOperation.Complete(OperationErrorStatus errorStatus)

at System.Windows.Ria.DomainContext.<>c__DisplayClassb.<SubmitChanges>b__3(Object )