Hello WCF RIA ServicesAn introduction to RIA Services
Gill CleerenMicrosoft Regional Director
Silverlight MVPOrdina Belgium
Glad to meet you...• Gill Cleeren• Microsoft Regional Director• Silverlight MVP• Telerik Insider & MVP• .NET Architect @Ordina (www.ordina.be) • Speaker (TechDays BE-NL-UK-SE-CH..., TechEd Berlin, DevDays, NDC Norway,
Spring Conference UK, SQL Server Saturday Switzerland...)• Visug user group lead (www.visug.be)• Author (Silverlight 4 Data and services cookbook)• www.snowball.be - [email protected] - @gillcleeren
Agenda• Part 1: Introduction to WCF RIA Services• Part 2: The basics of RIA Services• Part 3: Concepts explained• Part 4: What about MVVM?• Part 5: Let’s validate!
PART 1: INTRODUCTION TO WCF RIA SERVICES
Database
Web servic
e
TrustBoundary
Data acces
s layer
App logic
App logic
View
The situation of the problem…
What is WCF RIA services exactly then?
Framework: WCF RIA Services provide end-to-end use of dataRetrieved by DAL of choice, shaped in BLL, annoted for validationData and metadata can flow over tiers through controlled set of operations
Tools: build multiple tiers togetherCode is generated on the client
Services: common services such as authentication can be reusedBased on ASP.NET foundation
Framework, tools and services withprescriptive pattern for n-tier applications
Why WCF RIA Services?• Less plumbing code to write• Prescriptive approach for working with data on
the client side• Makes working with WCF easier, hides details• Makes using LINQ possible in n-tier scenarios• Client side framework for service calls, validation
and security
• End-to-end view of an application: – Framework– Tooling – Services
• Prescriptive approach to app logic • DAL-neutral and targets multiple presentation technologies• Make RIA development as productive as ASP.NET development• .NET on server and on client
Important design principles
Being neutral
AppLogic
DatabasesADO.NET,ORMs (LTS, EF, …)
Lists/ObjectsRepository(NHibernate, …)
ServicesREST/SOAP(Azure, …)
.NET ClientsSilverlight,WPF (hopefully phone)Standards ClientsJavaScriptServer RenderingHTML, Sitemaps
ServicesSOAP, XML,JSON, OData Unit Test
Code
How do I get WCF RIA Services?• If you have Silverlight tools installed, you have RIA
Services already • Additional download: RIA Services Toolkit
– Adds support for other endpoint types (SOAP, JSON)– ASP.NET support for consuming domain service in process
• WCF RIA Services SP1– We’ll look at this later!
PART 2: THE BASICS OF WCF RIA SERVICES
The Dev Process: Server-Side
1 2 3 4
Create Business
Application
Create Entity Model
Create Domain Service
Add/generatequeries
5Modify
Metadata
DEMOCreating the server-side
The Dev Process: Client-Side
Use Data Sources window
2
Drag on the interface
31
Generate DomainDataSource
Success!
4
Note that this is just
one way of using RIA services
DEMOCreating the client-side
PART 3: CONCEPTS EXPLAINED
Concepts of RIA Services
Code generation
Domain Data source
ValidationMeta data
Querying
Shared code
Authentication
WCF RIA SERVICES
Domain Context
Server-side
Domain Service
Metadata Classes
Validation Attributes
Security Attributes Shared Code
Use query operations to read data
• Inside the service, we can query data– Query operations return object, IEnumerable<T> or
IQueryable<T>• IQueryable<T> and LINQ provider are required if we want to use
deferred execution
– Based on convention (GetXXX, RetrieveXXX…)• If convention isn’t possible, use Query attribute• Other attributes exist:
– IsComposable=false when returning single entity– ResultLimit to constrain maximum items returned to client
Let’s defer things• The use of IQueryable<T>: Deferred Execution
– RIA Services serializes the expression tree from the client the server
– LINQ operations specified by the expression tree are executed on the server
– When the underlying provider supports it (i.e. Entity Framework and LINQ to SQL), deferred execution goes all the way to the DB
Querying Relations• What if we want to return related entities in one
go?– Load all Hotels for a City– Step 1 (Entity Framework)
• ObjectContext.Cities.Include(“Hotels”)
– Step 2:• Entity metadata type needs [Include] attribute
on related property
Conventions can help us!• RIA Services uses naming conventions in domain service to
identify methods– Insert: InsertXXX, AddXXX, CreateXXX– Update: UpdateXXX, ModifyXXX, ChangeXXX– Delete: DeleteXXX, RemoveXXX– Where XXX is an entity type name
• If we want Dutch code (yes some people do that…), we can use Attributes– Insert, Update, Delete attributes
Metadata or buddy classes• Define a partial class for the entity type • Define a nested metadata class inside the entity type
– Not required, but convention– “Buddy class”
• Add a MetadataType attribute on the entity partial class to tie in the metadata type• Add attributes to properties on the metadata type that match the entity properties• Those attributes show up on the client entity type or influence entity transmission
– Validation– Include– Exclude– Composition
Client-side
Domain Context
Entity Query Entity Load Operation
Submit Operation
Client-side generated entities• On the client, entities get generated (code-generation)
– Entity Framework or LINQ to SQL entities supported automatically
– POCOs must follow certain conventions• Must have a [Key] property• Relation properties must have an [Association] attribute to
indicate the related property type’s key fields• Need [Include] attribute on properties to child entity
collections or single entities to have them serialized
Loading Data on the Client• Option 1: what you CAN do: the DomainDataSource
– Allow you to execute a DomainContext method to query data• Including updates• Happens async
– Drag/drop data binding is VS 2010 generates XAML DomainDataSource and Grid
• (we’ve seen this in the demo)
– Supports parameterized queries– Supports sorting, grouping, filtering, pagingNot a good fit with MVVM
• Puts query “logic” into the view
Loading Data on Client• Option 2: What you SHOULD do: DomainContext.Load()
– Pass an EntityQuery<T>– Can modify the expression tree on client if target method in
DomainService returns IQueryable<T>– Executes asynchronously– Bind to entity collection for automatic update via INotifyCollectionChanged– Pass async callback to be notified and work with results or handle errors
yourself– Can work with returned LoadOperation<T>
for async notification as well
Update Operations• Implicit unit of work:
– Entity changes are cached in the client DomainContext until SubmitChanges called
Contains an EntityContainer for each entity type that tracks changes
• Sent as a batch to the service– Including original version for optimistic concurrency
• Service executes batch, calling Insert, Update, and Delete methods with one entity per method call
Security• Authentication• Roles• User profile• Declarative: class / method-level• Integrated into Query / Submit processing• All based on ASP.NET infrastructure
What is added with SP1?Cloud Ready
Complex Type
Support
Shared Entities
T4 Templates
DomainCollection
View
DEEP-DIVE DEMO
PART 4: WHAT ABOUT MVVM?
RIA Services and MVVM == BFF• Server-side: no changes, just create your services as
normal• Client-side:
– The generated entities are your model objects• They already implement INotifyPropertyChanged
– You get DomainContext • Your gateway to the web services• Change tracking
– Don’t use the DomainDataSource!
MVVM DEMO
PART 5:VALIDATION WITH WCF RIA SERVICES
Validation in Silverlight• Validation in Silverlight is based on the concept of data binding• Several options exist:
– IDataErrorInfo– INotifyDataErrorInfo
• INotifyDataErrorInfo supports async validation– When we set a value, it may be OK client-side but not server-side– An event is raised if server-side validation fails– Silverlight watches for this event being raised
• RIA Services Entity base class provides the implementation
INotifyDataErrorInfo interface
public interface INotifyDataErrorInfo {
bool HasErrors { get; } event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged; IEnumerable GetErrors(string propertyName);
}
RIA Services Validation OptionsWe have 3 options:1. DataAnnotations attributes2. Server update method exceptions3. Client async service method calls
Data Annotations Attributes• Live in System.ComponentModel.DataAnnotations namespace
– Also used by ASP.NET MVC and Dynamic Data• Contains a few standard attributes:
– [Required]– [Range]– [RegEx]– [StringLength]
• And then there’s the Custom one…– [CustomValidation]– Define static method with appropriate signature:public static ValidationResult ValidateCityName(string
newCityName, ValidationContext context)
Data Annotations how-to• WCF RIA Services will automatically evaluate data
annotation attributes on both client and server side• For Entity Framework generated types on server, define
metadata class and put attributes on its properties• Client generated entities contain same attributes• CustomValidation methods must be put in a .shared.cs
file so they get copied to the client side
Server Validation Exceptions• Some things have to be evaluated on the server
– Can wait until update batch is submitted to evaluate validation rules server side
– Throw ValidationException from insert, update, or delete method– RIA Services automatically associates the error with the individual
entity and hooks into the validation client side– Will still be raised as an exception from the SubmitChanges
method, must handle– Can also inspect properties of the SubmitOperation
• EntitiesInError collection
Client Async Calls• Expose [Invoke] methods on domain service• Call method with value to be changed, get
back result• Set validation errors manually
– Entity.ValidationErrors.Add
VALIDATION DEMO
Summary• RIA services opens up oppurtunity to build n-
tier apps with ease• Built on power of WCF• Key concepts explained• Works in combination with MVVM• Supports several validation types
Q&(HOPEFULLY)A
THANKS!
Hello WCF RIA Services
Gill CleerenMicrosoft Regional Director
Silverlight MVPOrdina Belgium
© 2008 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.
Partner logo to
go here