Your SlideShare is downloading. ×
Wcf data services
Upcoming SlideShare
Loading in...5

Thanks for flagging this SlideShare!

Oops! An error has occurred.


Saving this for later?

Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime - even offline.

Text the download link to your phone

Standard text messaging rates apply

Wcf data services


Published on

WCF Data Services (formerly known as "ADO.NET Data Services") is a component of the .NET Framework that enables you to create services that use the Open Data Protocol (OData) to expose and consume …

WCF Data Services (formerly known as "ADO.NET Data Services") is a component of the .NET Framework that enables you to create services that use the Open Data Protocol (OData) to expose and consume data over the Web or intranet by using the semantics of representational state transfer (REST). OData exposes data as resources that are addressable by URIs. Data is accessed and changed by using standard HTTP verbs of GET, PUT, POST, and DELETE. OData uses the entity-relationship conventions of the Entity Data Model to expose resources as sets of entities that are related by associations.

Published in: Technology

  • Be the first to comment

  • Be the first to like this

No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

No notes for slide


  • 1. WCF Data Services Eyal Vardi CEO E4D Solutions LTD Microsoft MVP Visual C# blog:
  • 2. Agenda
    • Services as Resources
    • URL Syntax
    • Client Applications of Data Services
    • CRUD API
    • ASP.NET AJAX Client Library
    • Advance Data Services
  • 3. The Goals
    • Expose data as a data service that can be consumed by web clients.
      • The data service is reachable over regular HTTP requests.
      • Standard HTTP verbs such as GET, POST, PUT and DELETE are used to perform CRUD operations against the service.
  • 4. Why Data Services
    • The use of web-friendly technologies make it ideal as a data back-end for:
      • AJAX-style applications
      • Rich Interactive Applications (Silverlight)
      • Other applications that need to operate against data that is across the web.
  • 5. Services Platform System.Net WCF Workflow Services Data Services Application / Service
  • 6. Data Services Architecture Iqueryable IUpdatable HTTP Request / Respond SQL Source Custom LINQ Provider Entity Framework Data Service Runtime Hosting / HTTP Listener
  • 7. Hello World
  • 8. Query string options
    • $Expand
      • /Customers(ALFKI)?$expand=Orders.Employees
    • $Orderby
      • /Customers?$orderby=City desc, CompanyName
    • $Skip
      • /Customers?$skip=10
    • $Top
      • /Orders?$orderby=TotalDue&$top=5
    • $Filter
      • /Customers?$filter=City eq ‘London’
  • 9. Expression Syntax Operator Description Example Logical Operators eq Equal /Customers?filter = City eq 'London' ne Not equal /Customers?filter = City ne 'London' gt Greater than /Product?$filter = UnitPrice gt 20 gteq Greater than or equal /Orders?$filter = Freight gteq 800 lt Less than /Orders?$filter = Freight lt 1 lteq Less than or equal /Product?$filter = UnitPrice lteq 20 and Logical and /Product?filter=UnitPrice lteq 20 and UnitPrice gt 10 or Logical or /Product?filter=UnitPrice lteq 20 or UnitPrice gt 10 not Logical negation /Orders?$ ?$filter=not endswith(ShipPostalCode,'100') Arithmetic Operators add Addition /Product?filter = UnitPrice add 5 gt 10 sub Subtraction /Product?filter = UnitPrice sub 5 gt 10 mul Multiplication /Orders?$filter = Freight mul 800 gt 2000 div Division /Orders?$filter = Freight div 10 eq 4 mod Modulo /Orders?$filter = Freight mod 10 eq 0 Grouping Operators ( ) Precedence grouping /Product?filter = (UnitPrice sub 5) gt 10
  • 10. Expression Syntax Cont. String Functions bool contains(string p0, string p1) bool endswith(string p0, string p1) bool startswith(string p0, string p1) int length(string p0) int indexof(string arg) string insert(string p0, int pos, string p1) string remove(string p0, int pos) string remove(string p0, int pos, int length) string replace(string p0, string find, string replace) string substring(string p0, int pos) string substring(string p0, int pos, int length) string tolower(string p0) string toupper(string p0) string trim(string p0) string concat(string p0, string p1) Date Functions int day(DateTime p0) int hour(DateTime p0) int minute(DateTime p0) int month(DateTime p0) int second(DateTime p0) int year(DateTime p0) Math Functions double round(double p0) decimal round(decimal p0) double floor(double p0) decimal floor(decimal p0) double ceiling(double p0) decimal ceiling(decimal p) Type Functions bool IsOf(type p0) bool IsOf(expression p0, type p1) <p0> Cast(type p0) <p1> Cast(expression p0, type p1)
  • 11. Data Services URL Syntax
  • 12. LINQ to URI
    • /ds.svc/Customers
      • from c in Customers select c
    • /ds.svc/Customers('ALFKI')
      • ( from c in Customers where c.keyProperty == &quot;ALFKI&quot; select c ).First()
    • /ds.svc/Customers('ALFKI')/Address
      • ( from c in Customers where c.keyProperty == &quot;ALFKI&quot; select c.Address ).First()
    • /ds.svc/Customers('ALFKI')/Orders
      • from c in Customers from c2 in c.Orders where c.keyProperty == &quot;ALFKI&quot; select c2
  • 13. Query Interceptors
    • Query interceptors are useful when you want to run your own custom methods when queries are executed against your entity sets.
    [QueryInterceptor(&quot;Employees&quot;)] public Expression<Func<Employees,bool>> FilterEmployees() { return e => e.EmployeeID > 0; }
  • 14. Change Interceptors
    • Change interceptors execute code during inserts, updates and deletes.
      • We can define a change interceptor to perform any validations etc during inserts, updates and deletes.
    [ChangeInterceptor(&quot;Customers&quot;)] public void AssignDefaultCountry(Customer c, UpdateOperations operation) {     if (operation == UpdateOperations.Add) {         if (c.Country.Trim().Length == 0) {             c.Country = &quot;UK&quot;;         }     } }
  • 15. Extending Data Services
    • You can extend ADO.NET Data Services by providing your own methods called as service operations to your data services.
    [WebGet] public IQueryable<Customer> GetCustomersByCity(string city) {     IQueryable<Customer> query =         from c in this.CurrentDataSource.Customers          where c.Country == city          select c;     return query; }
  • 16. Data Service Access Policy Rights Description None Denies all rights to access data. ReadSingle Authorization to read single data items. ReadMultiple Queries for the entire contents of the set are allowed. AllRead Shorthand for ReadSingle | ReadMultiple WriteAppend Authorization to create new data items in data sets. WriteReplace Authorization to replace data. WriteDelete Authorization to delete data items from data sets. WriteMerge Shorthand for WriteDelete| WriteReplace| WriteAppend. AllWrite Authorization to write data. All Authorization to create, read, update, and delete data.
  • 17. Example public class Northwind : DataService<NorthwindEntities> { public static void InitializeService( IDataServiceConfiguration config) { config.SetEntitySetAccessRule( &quot;*&quot;, EntitySetRights.All ); config.SetServiceOperationAccessRule( &quot;GetEmployee&quot;, ServiceOperationRights.All); } }
  • 18. IDataServiceConfiguration
  • 19. Extending Data Services
  • 20. In Memory Data
    • ADO.NET Data Services is very extensible and can work with in-memory data (such as a list of objects) as well as data from databases.
    public class CustomerContainer {     private List<Customer> customers = new List<Customer>();     public IQueryable<Customer> Customers     {         get{ return customers.AsQueryable(); }     } }
  • 21. Derive Data Service Class
    • CreateDataSource()
      • Creates a data source of the template class that will be used by the data service.
    • HandleException ( HandleExceptionArgs args )
      • Called when an exception is thrown while processing a request.
    • OnStartProcessingRequest ( ProcessRequestArgs args )
      • Called before processing each request. For batch requests, it is called once for the top batch request and once for each operation in the batch.
  • 22. Derive DataService Class
  • 23. Custom Provider ( IUpdatable )
    • The main design goals of IUpdatable interface is to make it resource independent.
      • The methods that return objects representing resources can return anything.
    • The actual implementation of IUpdatable needs to track the mapping between the opaque object to the actual object it represents.
  • 24. IUpdatable
  • 25. IUpdatable
  • 26. Entity Customization
    • ETag Attribute
    • IgnoreProperties Attribute
    • MimeType Attribute
    • SingleResult Attribute
  • 27. Data Services Client Library
  • 28. Client API
    • The goal of System.DataServices.Client is:
      • Object deserialization
      • Lazy loading
      • Identity tracking
      • Change tracking
    DataServiceContext context = new DataServiceContext( new Uri( &quot;http://localhost:5000/Northwind.svc&quot; ) );
  • 29. Object Deserialization
    • ADO.NET Data Services comes with a tool to generate your client-side model. (DataSvcUtil.exe)
    Uri ds = new Uri( &quot;; ); DataServiceContext context = new DataServiceContext( ds ); DataServiceQuery<Employees> employees = context.CreateQuery<Employees>( &quot;Employees?$filter= EmployeeID gt 5&quot; );
  • 30. Lazy Loading
    • $extend
    • LoadProperty
    Uri ds = new Uri( &quot;; ); DataServiceContext context = new DataServiceContext( ds ); DataServiceQuery<Employees> employees = context.CreateQuery<Employees>(&quot;/Employees&quot;); foreach (var item in employees) { // item.Orders.Count = 0. context.LoadProperty(item, &quot;Orders&quot;); // item.Orders.Count = ?. }
  • 31. Identity Tracking
    • DataServiceContext class has identity tracking built into it.
    • If you request object, and then request the same object again, it will be smart enough to give you the existing instance and not make the service call .
      • Context.MergeOption = MergeOption.AppendOnly;
  • 32. Identity Tracking MergeOption Member Description AppendOnly Objects that already exist in the DataServiceContext are not loaded from persisted storage. This is the default behavior for queries or when calling the Load method on an EntityCollection<(Of <(TEntity>)>) . OverwriteChanges Objects are always loaded from persisted storage. Any property changes made to objects in the DataServiceContext are overwritten by the storage values. PreserveChanges When an object exists in the DataServiceContext , it is not loaded from persisted storage. Any property changes made to objects in the DataServiceContext are preserved. This is used to force changes to objects in the DataServiceContext to save successfully after an OptimisticConcurrencyException has occurred. For more information, see Saving Changes and Managing Concurrency in the ADO.NET Entity Framework documentation. NoTracking Objects are maintained in a Detached state and are not tracked in the ObjectStateManager .
  • 33. Change Tracking
    • Make a bunch of changes in a single session and then submit all those changes for persistence in one swoop.
      • DataServiceContext .SaveChanges( SaveChangesOptions options );
  • 34. CRUD API Method
      • Description
      • AddObject
      • Adds a newly created object.
      • AttachTo
      • Start tracking object.
      • UpdateObject
      • Marks an object as changed.
      • DeleteObject
      • Marks the object for deletion.
      • AddLink
      • Adds a link between two objects.
      • AttachLink
      • Start tracking between two objects.
      • UpdateLink
      • Updates a link between two objects.
      • DeleteLink
      • Deletes a link between two objects.
  • 35. Silverlight API
  • 36. AJAX API