practical odata

44
Practical OData with and without XYZ Vagif Abilov Miles AS [email protected] @ooobject github: object http://bloggingabout.net/blogs/vagif/

Upload: vagif-abilov

Post on 27-Jan-2015

155 views

Category:

Spiritual


11 download

DESCRIPTION

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)

TRANSCRIPT

  • 1. Vagif AbilovMiles [email protected]@ooobjectgithub: objecthttp://bloggingabout.net/blogs/vagif/

2. ODataand 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. Are you familiar with OData? Have you used OData in your projects?Do you have components on your machine that use OData communication? 4. The Open Data Protocol (OData) is a Webprotocol for querying and updating data Consumers query a datasource over HTTPand get results back in formats likeAtomPub, JSON or plain XML OData follows many of the principles ofREST 5. Querying NuGet feed with LINQPadImporting data from OData feed into Microsoft Excel using PowerPivot 6. Command content specified in URIs Use of HTTP verbs (GET, POST, PUT,DELETE) Use of HTTP status codes Response sent as XML (AtomPub) orJSON Related content specified using linkelements 7. HypermediaHTTP URI 8. Method Safe IdempotentGETYes YesPOST NoNoPUTNoYesDELETE NoYes 9. http://localhost:50555/InMemory.svc/Customers(ALFKI)http://localhost:50555/InMemory.svc/Customers()?$filter=CompanyName eqAlfreds Futterkistehttp://localhost:50555/InMemory.svc/Customers()?$expand=Orders 10. http://localhost.:50555/InMemory.svc/CustomersMyCompanyTEMP 11. http://localhost.:50555/InMemory.svc/Customers(TEMP)My NewCompanyTEMP 12. http://localhost.:50555/InMemory.svc/Customers(TEMP) 13. Request: a company with non-existingCompanyNameResponse: an empty collectionRequest: a company with non-existingCompanyIDResponse: 404 Not Found 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. Formerly ADO.NETData Services Codename Astoria OData provider library for .NET Not to be confused with WCF RIA Servicesdesigned specifically for end-to-endSilverlight and ASP.NET applications 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 IQueryableproperties easy Implementing IUpdatable for updatable ODatafeeds easy Using custom provider OData provider toolkit usually helps still complex 17. public class EntityFrameworkModelFirstMsSql :DataService{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. As simple as with MS SQL assuming EFprovider for the respective vendor isavailable Proven choice: Devart dotConnect productfamily: Oracle MySQL PostgreSQL SQLite 19. Not supported by tools EDMX is just an XML file with 3 mainsections: 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. DbContext class, wraps ObjectContext Model is generated from entities Database can be generated from themodel Convention over configuration reducesconfiguration code to bare minimum No more trick to share conceptual modelbetween databases from different vendors 21. public class NorthwindContextBase : DbContext{public ObjectContext ObjectContext{ get { return (this as IObjectContextAdapter).ObjectContext; }}}public class EntityFrameworkCodeFirstMsSql : DataService{protected override ObjectContext CreateDataSource(){ var ctx = new NorthwindContext("NorthwindContext.EF.CF.MsSql"); return ctx.ObjectContext;}} 22. Suitable for most of scenarios with staticresource set information (schema knownat compile time) Resource sets exposed as IQueryableproperties of the context class DataServiceKey attribute specifies entitykey Optional support for IUpdatable 23. OData feed exposingin-memory data collectionOData feed using NHibernate to accessMS SQL database 24. Entity Framework provider is the quickestway to add OData feed on the top of apopular SQL database Reflection provider covers most of otherscenarios when the data schema is knownup-front Custom provider is needed when theschema is discovered at runtime or datadont have fixed types 25. If the content of NoSQL database is knownat compile time, reflection provider can beused If the content of NoSQL database isdivided into collections of fixed types, theresource sets can be built at runtime If the content is untyped, OData feed canstill be built using open types 26. Creating OData feed for MongoDBusing WCF Data Services and OData Provider Toolkit 27. OData data model supports open types forEntries. An entry of an open type mayhave extra properties (dynamic properties)in addition to those statically declared inmetadata WCF Data Services framework takes careof transforming the incoming requests intoan expression tree. Custom code isresponsible for evaluation expression treeagainst the data store 28. Custom service operations can only useHTTP GET and POST Generated client context code does notinclude custom service operations it hasto be added manually Default webHttpBinding settings may notbe sufficient for large payload(send/receiveTimeout, maxBufferSize andmaxStringContentLength often need to beincreased) 29. [WebInvoke(Method = "POST")]public void DeleteProductsByNamePattern(string namePattern){this.CurrentDataSource.ExecuteStoreCommand( string.Format("DELETE FROM Products WHERE ProductName LIKE {0}%", namePattern));} 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. ODatadesign goal is to provide datapublishing protocol for services, not forlow-level components Dont use OData to implement cascadedupdates and deletes of large number ofdependent entities Understand the difference between client-side and server-side operations 32. LINQPad (LINQ to OData) Fiddler RedGate .NET Reflector Pro (to step-in toWCF Data Services code) Oren Einis profilers (EF Profiler,NHibernate Profiler) Elmah logging framework (install it usingNuGet, it will update your web.config) 33. Dont reinvent the wheel, dont come withyour own standards Consider OData to expose data sourceson the Web Dont treat OData as a SQL databasepublisher Writing OData feeds is easy 34. Code examples for this presentation:https://github.com/object/NorthwindOData Open Data Protocol:http://www.odata.org/http://www.odata.org/mailing-list WCF Data Services forum:http://social.msdn.microsoft.com/Forums/en/adodotnetdataservices/ 35. WCFData Services Toolkit:http://wcfdstoolkit.codeplex.com/ Microsoft WCF Data Services March 2011CTP 2 for .NET Framework 4 andSilverlight 4:http://www.microsoft.com/downloads/en/details.aspx?FamilyID=60fb0117-8cea-4359-b392-6b04cdc821be 36. OData!(Lennon McCartney) 37. OData! Please relieve meAtomPub is what Im gonna needBelieve me when I tell you:AtomPub is what Im gonna need 38. OData! Please relieve meJSONs what I want in JavaScriptBelieve me when I tell you:JSONs what I want in JavaScript 39. When you told me:Internal error 500Oh well you know,I nearly broke down and criedWhen you told me:Internal error 501Oh well you know,I nearly broke down and died 40. OData! Please relieve meI want to live a RESTful lifeBelieve me when I tell you:I want to live a RESTful life 41. VagifAbilov Miles AS [email protected] @ooobject github: object http://bloggingabout.net/blogs/vagif/