490 likes | 697 Views
Hello WCF RIA Services An introduction to RIA Services. Gill Cleeren Microsoft Regional Director Silverlight MVP Ordina Belgium. Gill Cleeren Microsoft Regional Director Silverlight MVP Telerik Insider & MVP .NET Architect @Ordina ( www.ordina.be )
E N D
Hello WCF RIA ServicesAn introduction to RIA Services Gill Cleeren Microsoft Regional Director Silverlight MVP Ordina Belgium
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 - gill@snowball.be- @gillcleeren Glad to meet you...
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!
The situation of the problem… Trust Boundary Web service Data access layer App logic App logic View Database
Framework: WCF RIA Services provide end-to-end use of data Retrieved by DAL of choice, shaped in BLL, annoted for validation Data and metadata can flow over tiers through controlled set of operations Tools: build multiple tiers together Code is generated on the client Services: common services such as authentication can be reused Based on ASP.NET foundation What is WCF RIA services exactly then? Framework, tools and services with prescriptive 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
Important design principles • 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
Being neutral Databases ADO.NET, ORMs (LTS, EF, …) .NET Clients Silverlight, WPF (hopefully phone) Standards Clients JavaScript App Logic Lists/Objects Repository (NHibernate, …) Server Rendering HTML, Sitemaps Services REST/SOAP (Azure, …) Services SOAP, 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!
The DevProcess: Server-Side Create Business Application Create Entity Model Create Domain Service 4 3 1 2 Add/generatequeries 5 ModifyMetadata
The DevProcess: Client-Side Use Data Sources window Drag on the interface 1 2 3 Note that this is just one way of using RIA services Generate DomainDataSource 4 Success!
Concepts of RIA Services Shared code Code generation Domain Data source WCF RIA SERVICES Validation Meta data Querying Authentication Domain Context
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 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, paging Not 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
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!
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 publicinterfaceINotifyDataErrorInfo { bool HasErrors { get; } eventEventHandler<DataErrorsChangedEventArgs> ErrorsChanged; IEnumerable GetErrors(string propertyName); }
RIA Services Validation Options We have 3 options: 1. DataAnnotations attributes 2. Server update method exceptions 3. 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
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
Hello WCF RIA Services Gill Cleeren Microsoft Regional Director Silverlight MVP Ordina 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