Practical OData

4.980 Aufrufe
4.715 Aufrufe

Veröffentlicht am

The outline of the presentation (presented at NDC 2011, Oslo, Norway):

- Short summary of OData evolution and current state
- Quick presentation of tools used to build and test OData services and clients (Visual Studio, LinqPad, Fiddler)
- Definition of canonical REST service, conformance of DataService-based implementation
- Updateable OData services
- Sharing single conceptual data model between databases from different vendors
- OData services without Entity Framework (NHibernate, custom data provider)
- Practical tips (logging, WCF binding, deployment)

Veröffentlicht in: Seele & Geist, Technologie
1 Kommentar
6 Gefällt mir
Keine Downloads
Aufrufe insgesamt
Auf SlideShare
Aus Einbettungen
Anzahl an Einbettungen
Gefällt mir
Einbettungen 0
Keine Einbettungen

Keine Notizen für die Folie

Practical OData

  1. 1. Vagif AbilovMiles object
  2. 2.  OData and REST WCF Data Services OData feed in 5 minutes: EF + MS SQL The power of ObjectContext Using reflection provider Using custom providers and NoSQL Extending OData services Performance and diagnostics A song about OData
  3. 3. Are you familiar with OData? Have you used OData in your projects?Do you have components on your machine that use OData communication?
  4. 4.  The Open Data Protocol (OData) is a Web protocol for querying and updating data Consumers query a datasource over HTTP and get results back in formats like AtomPub, JSON or plain XML OData follows many of the principles of REST
  5. 5. Querying NuGet feed with LINQPadImporting data from OData feed into Microsoft Excel using PowerPivot
  6. 6.  Command content specified in URIs Use of HTTP verbs (GET, POST, PUT, DELETE) Use of HTTP status codes Response sent as XML (AtomPub) or JSON Related content specified using link elements
  7. 7. Hypermedia HTTP URI
  8. 8. Method Safe IdempotentGET Yes YesPOST No NoPUT No YesDELETE No Yes
  9. 9. http://localhost:50555/InMemory.svc/Customers(ALFKI)http://localhost:50555/InMemory.svc/Customers()?$filter=CompanyName eqAlfreds Futterkiste„http://localhost:50555/InMemory.svc/Customers()?$expand=Orders
  10. 10. http://localhost.:50555/InMemory.svc/Customers<entry term="Northwind.InMemory.Customers" /> <content type="application/xml"> <m:properties> <d:CompanyName>MyCompany</d:CompanyName> <d:CustomerID>TEMP</d:CustomerID> </m:properties> </content></entry>
  11. 11. http://localhost.:50555/InMemory.svc/Customers(„TEMP)<entry term="Northwind.InMemory.Customers" /> <content type="application/xml"> <m:properties> <d:CompanyName>My NewCompany</d:CompanyName> <d:CustomerID>TEMP</d:CustomerID> </m:properties> </content></entry>
  12. 12. http://localhost.:50555/InMemory.svc/Customers(„TEMP)
  13. 13. Request: a company with non-existingCompanyNameResponse: an empty collectionRequest: a company with non-existingCompanyIDResponse: 404 Not Found
  14. 14. var ctx = new NorthwindContext("http://localhost.:50555/InMemory.svc");ctx.IgnoreResourceNotFoundException = true;var customers = from c in ctx.Customers where c.CustomerID == "XYZ" select c;
  15. 15.  Formerly ADO.NET Data Services Codename “Astoria” OData provider library for .NET Not to be confused with WCF RIA Services designed specifically for end-to-end Silverlight and ASP.NET applications
  16. 16.  Using Entity Framework provider • EF model first+ MS SQL – trivial • EF code first, different DB vendors – easy Using reflection provider • Any context exposing a set of IQueryable properties – easy • Implementing IUpdatable for updatable OData feeds – easy Using custom provider • OData provider toolkit usually helps – still complex
  17. 17. public class EntityFrameworkModelFirstMsSql :DataService<NorthwindMsSqlContext>{ public static void InitializeService(DataServiceConfiguration config) { config.SetEntitySetAccessRule("*", EntitySetRights.All); config.SetServiceOperationAccessRule("*", ServiceOperationRights.All); config.DataServiceBehavior.MaxProtocolVersion =DataServiceProtocolVersion.V2; } protected override NorthwindMsSqlContext CreateDataSource() { return new NorthwindMsSqlContext(/* connection string */); }}
  18. 18.  As simple as with MS SQL assuming EF provider for the respective vendor is available Proven choice: Devart dotConnect product family: • Oracle • MySQL • PostgreSQL • SQLite
  19. 19.  Not supported by tools EDMX is just an XML file with 3 main sections: • Conceptual model (CSDL) • Storage model (SSDL) • Mapping (MSL) You can author your own EF model: • Support for n database vendors • 2n + 1 XML sections (1 CSDL + n SSDL + n MSL)
  20. 20.  DbContext class, wraps ObjectContext Model is generated from entities Database can be generated from the model Convention over configuration reduces configuration code to bare minimum No more trick to share conceptual model between databases from different vendors
  21. 21. public class NorthwindContextBase : DbContext{ public ObjectContext ObjectContext { get { return (this as IObjectContextAdapter).ObjectContext; } }}public class EntityFrameworkCodeFirstMsSql : DataService<ObjectContext>{ protected override ObjectContext CreateDataSource() { var ctx = new NorthwindContext("NorthwindContext.EF.CF.MsSql"); return ctx.ObjectContext; }}
  22. 22.  Suitable for most of scenarios with static resource set information (schema known at compile time) Resource sets exposed as IQueryable<T> properties of the context class DataServiceKey attribute specifies entity key Optional support for IUpdatable
  23. 23. OData feed exposingin-memory data collection OData feed using NHibernate to access MS SQL database
  24. 24.  Entity Framework provider is the quickest way to add OData feed on the top of a popular SQL database Reflection provider covers most of other scenarios when the data schema is known up-front Custom provider is needed when the schema is discovered at runtime or data don‟t have fixed types
  25. 25.  If the content of NoSQL database is known at compile time, reflection provider can be used If the content of NoSQL database is divided into collections of fixed types, the resource sets can be built at runtime If the content is untyped, OData feed can still be built using open types
  26. 26. Creating OData feed for MongoDB using WCF Data Services and OData Provider Toolkit
  27. 27.  OData data model supports open types for Entries. An entry of an open type may have extra properties (dynamic properties) in addition to those statically declared in metadata WCF Data Services framework takes care of transforming the incoming requests into an expression tree. Custom code is responsible for evaluation expression tree against the data store
  28. 28.  Custom service operations can only use HTTP GET and POST Generated client context code does not include custom service operations – it has to be added manually Default webHttpBinding settings may not be sufficient for large payload (send/receiveTimeout, maxBufferSize and maxStringContentLength often need to be increased)
  29. 29. [WebInvoke(Method = "POST")]public void DeleteProductsByNamePattern(string namePattern){ this.CurrentDataSource.ExecuteStoreCommand( string.Format("DELETE FROM Products WHERE ProductName LIKE {0}%", namePattern));}
  30. 30. public void DeleteProductsByNamePattern(string namePattern){ HttpWebRequest request = (HttpWebRequest)WebRequest.Create( string.Format("{0}/DeleteProductsByNamePattern?namePattern={1}", this.BaseUri, namePattern)); request.Method = "POST"; request.Accept = "application/atom+xml,application/xml"; request.ContentType = "application/atom+xml"; request.ContentLength = 0; HttpWebResponse response = (HttpWebResponse)request.GetResponse();}
  31. 31.  OData design goal is to provide data publishing protocol for services, not for low-level components Don‟t use OData to implement cascaded updates and deletes of large number of dependent entities Understand the difference between client- side and server-side operations
  32. 32.  LINQPad (LINQ to OData) Fiddler RedGate .NET Reflector Pro (to step-in to WCF Data Services code) Oren Eini‟s profilers (EF Profiler, NHibernate Profiler) Elmah logging framework (install it using NuGet, it will update your web.config)
  33. 33.  Don‟t reinvent the wheel, don‟t come with your own standards Consider OData to expose data sources on the Web Don‟t treat OData as a SQL database publisher Writing OData feeds is easy
  34. 34.  Code examples for this presentation: NorthwindOData Open Data Protocol: WCF Data Services forum: n/adodotnetdataservices/
  35. 35.  WCF Data Services Toolkit: Microsoft WCF Data Services March 2011 CTP 2 for .NET Framework 4 and Silverlight 4: tails.aspx?FamilyID=60fb0117-8cea-4359- b392-6b04cdc821be
  36. 36. OData!(Lennon – McCartney)
  37. 37. OData! Please relieve meAtomPub is what I‟m gonna needBelieve me when I tell you:AtomPub is what I‟m gonna need
  38. 38. OData! Please relieve meJSON‟s what I want in JavaScriptBelieve me when I tell you:JSON‟s what I want in JavaScript
  39. 39. When you told me:“Internal error 500”Oh well you know,I nearly broke down and criedWhen you told me:“Internal error 501”Oh well you know,I nearly broke down and died
  40. 40. OData! Please relieve meI want to live a RESTful lifeBelieve me when I tell you:I want to live a RESTful life
  41. 41.  Vagif Abilov Miles AS @ooobject github: object