Book Image

OData Programming Cookbook for .NET Developers

By : Juntao Cheng
Book Image

OData Programming Cookbook for .NET Developers

By: Juntao Cheng

Overview of this book

Odata (Open Data Protocol) is a Web protocol for querying and updating data that provides a way to unlock your data and free it from silos that exist in applications today. OData enables data access among a variety of applications, services, and stores by adopting existing Web technologies such as HTTP, XML, and JSON. This book deals with common OData programming cases over the Microsoft .NET Framework platform and eases the learning curve for a .NET developer to start incorporating OData in data service development.This book provides a collection of recipes that help .NET developers to get familiar with OData programming in a quick and efficient manner. The recipes cover most OData features from the former ADO.NET Data Service to the current WCF Data Service platform. In addition, all the sample cases here are based on real-world scenarios and issues that .NET developers might come across when programming with OData in application development.This book will be your handy guide with basic to advanced walkthroughs of common OData programming cases for the Microsoft .NET Framework platform. You will learn quick solutions to necessary tasks to integrate the power of OData at both server-side and client-side.This book will help you master the use of OData with .NET Framework by taking you through hands-on and practical recipes. It starts by talking about the common means for building OData services and consuming OData services in client applications. Then, some more specific topics like hosting, configuration and security are discussed. The book also covers many popular and interesting topics such as integrating OData in web applications, and developing data-driven mobile applications with OData. Moreover, you can also find quite a few recipes discussing real-world OData producers and new features in latest and future versions.Within "OData Programming Cookbook for .NET Developers", all the recipes are selected based on real-world scenarios that you will commonly come across. Each recipe covers a specific topic, going from the description of the problem, through a conceptual solution, to a solution containing sample code. By following these recipes, you can acquire how to program with OData in a simple, effective, and easy manner.
Table of Contents (15 chapters)
OData Programming Cookbook for .NET Developers
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface

Using Interceptors to customize a WCF Data Service


If you've been familiar with standard WCF service programming, you probably have been playing with the Message Inspectors, which are one of the WCF extension components for intercepting the request and response messages of service operation calls.

Well, for WCF Data Service, we also have the similar extension component called Interceptors, which can help intercepting the service requests issued from client callers.

By using WCF Data Service Interceptors, we can customize the code logic of certain operations against a given entity set. In this recipe, we will see how to do some customization on the data processing code logic in WCF Data Service by using custom Interceptors.

Getting ready

In this recipe we will build a WCF Data Service based on the Northwind EF data model. The service will expose two data entity sets, one is from the Categories table, and the other is from the Products table. For demonstration, we will add two custom Interceptors against these two entity sets so as to change their query and delete behavior.

The source code for this recipe can be found in the \ch01\QIDataServiceSln\ directory.

How to do it...

  1. 1. Create a new ASP.NET Empty Web Application.

  2. 2. Create a WCF Data Service with ADO.NET Entity Framework data model (using the Northwind database).

    The service will only expose the Categories and Products entity sets from the data source (see the following screenshot).

  3. 3. Add custom Interceptors in the WCF Data Service class and bind them with the target entity sets.

    There are two Interceptors to define here. The first one is a QueryInterceptor against the Products entity set. It will restrict the query result so as to expose Product entities that have UnitsInStock > 0. The second one is a ChangeInterceptor against the Categories entity set. By using it, no delete operation is allowed on the Categories entity set. The following code snippet shows the WCF Data Service class, which includes both Interceptors:

    public class NWDataService : DataService< NorthwindEntities >
    {
    public static void InitializeService(DataServiceConfiguration config)
    {
    config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
    config.SetEntitySetAccessRule("*", EntitySetRights.All);
    }
    // Query Interceptor for Products entity set
    [QueryInterceptor("Products")]
    public Expression<Func<Product, bool>> onQueryProducts()
    {
    // Only return products that have units in stock
    return p => p.UnitsInStock > 0;
    }
    // Change Interceptor for Categories entity set
    [ChangeInterceptor("Categories")]
    public void onChangeCategories (Category cate, UpdateOperations operations)
    {
    if (operations == UpdateOperations.Delete)
    {
    throw new DataServiceException(400, "Delete operation is not supported on Categories entity set.");
    }
    }
    }
    
  4. 4. Launch the service and try accessing the entity sets, which have Interceptors applied.

    By accessing the Products entity set, we can find that all the entities returned by it have the UnitsInStock field greater than zero. Also, if we explicitly use query filter to look for Product entities that have UnitsInStock equal to zero, we will get empty results (see the following screenshot).

How it works...

In the sample service, we have applied a QueryInterceptor on the Products entity set. Actually, a QueryInterceptor is just a function, which returns a Lambda expression with the following signature:

Func<[Entity Type], bool>

Then, why does it use an expression instead of a delegate function directly? The reason is that by using an expression, it is more convenient for the underlying WCF Data Service runtime to forward such QueryInterceptor injected code logic to the actual query provider (such as the ADO.NET Entity Framework provider, which will generate T-SQL based on the query) that will fetch the data from the backend data source.

QueryInterceptor will be invoked when HTTP GET based query requests are received against the target entity set; while ChangeInterceptor will be invoked when update/modify operations are called. In this sample, our onChangeCategories Interceptor will check the incoming request to see if it is a delete operation against the Categories entity set. If the checking result is true, a DataServiceException will be thrown out. In a real-world case, we can apply more complicated code logic to change the default update/modify behavior against the target entity sets.

There's more...

For more information about using Interceptors in WCF Data Service, you can read the following MSDN reference:

Interceptors (WCF Data Services) available at http://msdn.microsoft.com/en-us/library/dd744842.aspx

See also

  • Building an OData service via WCF Data Service and ADO.NET Entity Framework recipe