A common misconception is to think that a WCF proxy can be used and disposed as any other regular class that implements IDisposable. However, the IDisposable implementation in the WCF client channel is not like any other, and it can throws exceptions. A phrase I got from this thread in the WCF forum will give you a better context about this scenario,

“I think a key thing to notice is that Close() often implies doing "real work" that may fail, including network communication handshakes to shutdown sessions, committing transactions, etc.”

As consequence of this, we should add some code to handle any possible exception for network errors when a proxy is closed/disposed.

The common pattern for cleaning up a proxy is the following,

try
{
...
client.Close();
}
catch (CommunicationException e)
{
...
client.Abort();
}
catch (TimeoutException e)
{
...
client.Abort();
}
catch (Exception e)
{
...
client.Abort();
throw;
}

The problem is, I do not want to have that code everywhere in my application. A good solution for that is to use a helper class like this one.

Michelle recently announced a new project that automatically generates a proxy helper class like that in Visual Studio. http://wcfproxygenerator.codeplex.com/

That is a feature I would like to see out of the box in the next version of WCF :).

Do you want to see something very ugly ?. Try to send a complete EF entity directly as a data contract over the wire with WCF,

<Order xmlns:i="http://www.w3.org/2001/XMLSchema-instance" z:Id="i1" xmlns:z="http://schemas.microsoft.com/2003/10/Serialization/" xmlns="http://schemas.datacontract.org/2004/07/ClassLibrary2">
  <EntityKey xmlns:d2p1="http://schemas.datacontract.org/2004/07/System.Data" i:nil="true" xmlns="http://schemas.datacontract.org/2004/07/System.Data.Objects.DataClasses" />
  <Description>My new order</Description>
  <OrderId>1</OrderId>
  <OrderItem>
    <OrderItem z:Id="i2">
      <EntityKey xmlns:d4p1="http://schemas.datacontract.org/2004/07/System.Data" i:nil="true" xmlns="http://schemas.datacontract.org/2004/07/System.Data.Objects.DataClasses" />
      <Currency>USD</Currency>
      <Description>item 1</Description>
      <ItemId>1</ItemId>
      <Order z:Ref="i1" />
      <OrderReference xmlns:d4p1="http://schemas.datacontract.org/2004/07/System.Data.Objects.DataClasses">
        <d4p1:EntityKey xmlns:d5p1="http://schemas.datacontract.org/2004/07/System.Data" i:nil="true" />
      </OrderReference>
      <UnitPrice>10</UnitPrice>
    </OrderItem>
    <OrderItem z:Id="i3">
      <EntityKey xmlns:d4p1="http://schemas.datacontract.org/2004/07/System.Data" i:nil="true" xmlns="http://schemas.datacontract.org/2004/07/System.Data.Objects.DataClasses" />
      <Currency>USD</Currency>
      <Description>item 2</Description>
      <ItemId>2</ItemId>
      <Order z:Ref="i1" />
      <OrderReference xmlns:d4p1="http://schemas.datacontract.org/2004/07/System.Data.Objects.DataClasses">
        <d4p1:EntityKey xmlns:d5p1="http://schemas.datacontract.org/2004/07/System.Data" i:nil="true" />
      </OrderReference>
      <UnitPrice>145</UnitPrice>
    </OrderItem>
  </OrderItem>
</Order>

That is the result of serializing a complete object graph. I do not know what the folks in Microsoft were thinking when they decided to enable a feature like this. They made a good work teaching us about how evil Datasets were for interoperability with other platforms, and now they came up with a solution like this, no way.

I always like the idea of making boundaries explicit, that is the approach the WCF team took with the first version of the framework (Every data contract should be decorated with DataContract and DataMember attributes).  If you break that rule, you will end up with things like this.

I know this a solution for people that want to develop things quickly with no need to create DTOs, and do all the mapping stuff, but there are good tools and frameworks like AutoMapper to help with that. Or you can use ADO.NET Data Services today, which is also prepared to handle this kind of scenarios, all the transformations between layers are made by the framework itself, and still you get a very nice RESTful api. We still need some more features in ADO.NET DS to have a more complete framework, there is not good support today for injecting business logic, it can be done but it is complicated, it looks like the next version will address that aspect better.

Como Jesus menciono en su post “We are still hiring..”, en Tellago estamos buscando gente que quieran unirse a nuestro equipo de desarrollo. En estos momentos tenemos algunas posiciones para Arquitectos y Desarrolladores con buenos conocimientos de Biztalk e idioma ingles.

Si queres ser parte de una empresa joven, jugar con las ultimas tecnologias o involucrarte en proyectos con diversos equipos de trabajo en Microsoft, enviame tu curriculum a pablo [dot] cibraro [at] tellago [dot] com

Las posiciones pueden ser tanto en Buenos Aires como en los Estados Unidos.

ADO.NET Data services represent today one of the most powerful alternatives to build RESTful services in the .NET platform. This framework basically creates a RESTful API on top of any IQueryable data source. Most of the steps required to publish a set of resources through http and make them available for any client are automatically implemented. 

Only Entity Framework data models are supported out of the box as read/write data sources, and any other IQueryable data source is considered by default read only. If you want to perform write operations on any other data source different from Entity Framework, you have to implement an additional interface IUpdatable as it is showed in this post. (Update: The new CTP 1.5 seems to have a new class to implement custom data providers, I have not had a chance to play with it yet)

Usually, you will need to inject custom logic in the services for performing validations or implementing business rules.

ADO.NET services comes with two built-in extensibility points for adding custom logic or code to a service, Service Operations and Interceptors.

Service operations represent a simple way to define custom read/write views on top of the data source exposed by the service. It is intended to be used in scenarios where you need to create complex queries, or simple data aggregations that are not supported out of the box in framework. If you want to expose those queries directly as another resource in the service, you have to use service operations.

The classic example given to show this feature in action is a query that returns all the customers in an specific city. That query would be translated in a service operation as follow,

public class MyService : DataService<MyDataSource>
{
    // This method is called only once to initialize service-wide policies.
    public static void InitializeService(IDataServiceConfiguration config)
    {
        config.SetEntitySetAccessRule("Customers", EntitySetRights.AllRead);
        config.SetServiceOperationAccessRule("CustomersInCity", ServiceOperationRights.All);
    }

    [WebGet]
    public IQueryable<MyDataSource.Customers> CustomersInCity(string city)
    {
        return from c in this.CurrentDataSource.Customers
               where c.City == city
               select c;
    } 

}

As you can see in the code above, the service operation for this example is a simple method decorated with a WebGet attribute that returns an IQueryable implementation (With a pre-defined query in this example). The WebGet attribute specifies that  is a read-only view. As soon as we have that service running, you can navigate to that service operation with an URI like this,

http://localhost/MyService.svc/CustomersInCity?city=BuenosAires

Since you are returning an IQueryable implementation, you are also free to define additional transformations on top of this base query, such as projections, filtering, or ordering among others.

WebInvoke can be also used in case you want to implement a write operation. Since a service operation works as a black box, only the post verb is supported for WebInvoke, which means that you can not use other verbs like DELETE or PUT. Regarding this limitation, this is the answer you can find in the forums

“We currently support only POST and GET verbs on the service operations (even in the recently released CTP). Is there a reason why you want to support  DELETE verb on service operation? The main reason for not supporting all the verbs is that from the client side, discovery becomes a issue - there is no way to know what verb to send for a service operation. Also service operations are black box to us - so we try and categorized them into side-effecting and non-side effecting ones. We recommend to use GET for non-side effection service opertions and use POST for side-effecting ones.

Please let us know if you think there is a good reason why DELETE verb should be supported.

Thanks
Pratik”

Another problem with service operations is that only scalar values are supported as arguments. Therefore, you can not pass entities or complex data types as arguments to a service operation.

These limitations make hard to use service operations as a way to inject custom logic like validations or business rules into a data service.

Fortunately, there is another extensibility point that becomes handy at the moment of implementing this kind of logic, the Interceptors. There are two kind of built-in interceptors, Query Interceptors, and Change Interceptors.

A query interceptor represents a mechanism to change or transform the initial projection over an entity set. For example, if an user only allowed to see a subset of all the available data in an entity set, a query interceptor is the right place to filter the data for that user.

[QueryInterceptor("Orders")]
public Expression<Func<Orders, bool>> QueryOrders() {
  return o => o.Number > 100;
}

The syntax of a query interceptor is quite simple, you basically returns an expression that describes a function (the Func), which takes an input value (an order being evaluated) and returns a bool value (whether the order passes the filter or not). Since an expression is used there rather than a piece of code, that expression can be passed directly to the query provider, which ultimately will generate the appropriate SQL in the database server.

A change interceptor on the other hand, intercepts all the calls that generates changes in the data source exposed by the service. Therefore, this interceptor is the right mechanism for performing some validations before the data is changed in the data source. This is the place where we can enforce the business rules or validate the data for an specific entity set in our application (Entity set in this scenario also represents a collection of resources, where each resource is the entity itself).

[ChangeInterceptor("Orders")]
public void OnChangeOrders(Order o, UpdateOperations operation)
{
     if (operation == UpdateOperations.Add || operation == UpdateOperations.Change)
     {
        if (o.Number > 100)
        {
          throw new DataServiceException(400,
            "You are not allowed to create or change an order with number greater than 100");
        }
    }
}

A change interceptor method receives two arguments, the entity that will be persisted, and an enumeration UpdateOperations that specifies the operation currently performed on the entity. Possible values for this enumeration are, Add, Change and Delete.

This interceptor is not just to perform validations, you are still free to call additional services or change some data in the entity before it is persisted. However, this method call is synchronous, so you should be careful about executing long running code there.

After having playing with the current bits of OpenRasta (OR) for a while, I  am now able to see great advantages in using this framework over other existing frameworks for building RESTful services such as WCF or the ASP.NET MVC.

Let’s explore some of the good features that make OpenRasta an excellent alternative at the moment of developing RESTful services.

1. Clean separation of resource representation from service implementation

If we take a look at a service implementation in OR, the operations in a handler receive or return a resource, but they never specify the final representation of that resource. Resource representation is a pure responsibility of the encoders configured for service implementation (a handler in OR).

In that way, we have a service implementation completely reusable for different resource representations.

public class CustomerHandler

{

    public OperationResult Get(int customerId)

    {

        return new OperationResult.OK

        {  

            ResponseResource = "Customer with id " + customerId

        };

    }

}

Once we have the service implementation, we only need to configure the encoders for that service, which could be encoders for Xml, Json, Atom or any other representation. You are free to configure all the encoders you want for the same handler.

ConfigureServer(() => ResourceSpace.Has.ResourcesOfType<Customer>()

    .AtUri("/customer/{customerId}")

    .HandledBy<CustomerHandler>()

    .AndTranscodedBy<OpenRasta.Codecs.JsonDataContractCodec>(null));

This is a different story in WCF. First of all, the content type (Xml or Json) has to be specified as part of the operation definition. If we want to support different content types, we need to replicate the same operation only to change the content type. Although this point has been improved considerably in WCF 4.0, some service implementations are still absolutely tied to the resource representation. For example, an operation that returns syndications feeds. In WCF, we have to return a concrete implementation of System.ServiceModel.Syndication.SyndicationFeedFormatter. It is not a simple as return a collection of entities or resources and specify somewhere that we want to represent them as entries in a feed.

This works much better in ADO.NET data services, where you can just return a resource or a collection of resources, and the framework itself will chose the best representation according to what the client initially sent in the “Accept” header. That representation could be Json or Atom, nothing changes in the service implementation (which is also automatically implemented). However, ADO.NET data services provide few extensibility points today for injecting custom code, and that is probably a good reason to move to OpenRasta.

2. URI resolution

In OpenRasta, the URI resolution to a handler is also part of the service configuration. This gives a great flexibility to have many URIs that resolve to the same resource instance.

A typical example is a parent-child relationship, for instance, a customer/orders relationship.

You might want to have different URIs to get access to the orders,

Customer/1/Orders/1 => Give me the order number 1 for the customer with ID 1

Or you might want to access to the order directly

Orders/1 => Give me the order number 1

In OR, you have a single handler implementation for orders (order is the resource in this case), and multiple URIs that resolve to an operation in that particular handler.

ConfigureServer(() => ResourceSpace.Has.ResourcesOfType<Order>()

    .AtUri("/customer/{customerId}/Orders/{orderId}")

    .AndAt("/orders/{orderId}")

    .HandledBy<OrderHandler>()

    .AndTranscodedBy<OpenRasta.Codecs.JsonDataContractCodec>(null));

This is a problem in WCF because the URI template is tied to the operation definition, if you want to have different URIs for the same resource, you basically have to copy/paste the same operation just to change the URIs.

[WebGet(UriTemplate="/Orders/{orderId}")]

public Order GetOrderById(int orderId)

{

  //implementation

}

[WebGet(UriTemplate = "/Customers/{customerId}/Orders/{orderId}")]

public Order GetCustomerOrder(int customerId, int orderId)

{

  //implementation

}

So, you will have as many operations as URI and content types you want to support in the service.

El proximo miercoles 20 de mayo a las 3 PM (GMT-05:00 Colombia, Panama), voy a estar presentando un MSDN webcast acerca de OpenID, OAuth y Windows Live ID. El evento va a ser transmitido en castellano para la comunidad de latinoamerica, y se va a enfocar en las caracteristicas principales de estas soluciones/protocolos, como funcionan, y algunos escenarios en donde se pueden aplicar con exito.

El link al evento es el siguiente, http://msevents.microsoft.com/CUI/EventDetail.aspx?EventID=1032403625&Culture=es-AR 

Los espero.

On May 18th, I will officially become part of Tellago.  I will be joining a great team with people that I respect immensely like Jesus Rodriguez, DonXml, or Joe Klug to name a few. Thanks guys for give me this opportunity!!.

I am leaving Clarius after almost two years of service. I got involved in a lot of interesting projects there, and what is more important, I had a chance to work with an excellent team of “all-stars” developers. I would like to thank Clarius and wish them the best in the future!

OpenRasta (OR) is the name of a new open source framework for developing Restful applications (Web applications or services) created by Sebastien Lambla. As the ASP.NET MVC, this framework is also an implementation of the MVC pattern, which focus mainly on a good separation of concerns, and provide different extensibility points where the developer can plugging custom code at the moment of developing applications.

The framework is now on Beta 2 stage, Sebastien and other guys are currently working on improving the hosting infrastructure and public API. They are, of course, very open at this point to receive feedback or suggestions for new features, or improvements to existing ones. If you have some interest in participating of this project, you can start joining the mailing list.

In order to understand how OR works under the hood, I will start by describing some basic concepts that a developer should know to implement an application from scratch with this framework.

Handlers

A “handler” is one of the main building blocks in OR. It represents the implementation of the service itself, and it is generally mapped to single resource through an URI. Therefore, any access to an URI will get resolved by OR to an specific handler.

From an implementation point of view, a handler is simple class that expose methods for handling different http verbs. By convention, a method should be called as the Http verb that supports, for example, Get or Post. However, nothing prevent you from giving more friendly names to the methods (or handler operations), there is an special custom attribute “HttpOperationAttribute” that you can use to associate the method with an http verb.

public class CustomerHandler

{

    public Customer Get(int customerId)

    {

        return new Customer { FirstName = "foo", LastName = "bar" };

    }

    public OperationResult Put(int id, Customer customer)

    {

        return new OperationResult.Modified { ResponseResource = customer };

    }

    [HttpOperation(HttpMethod.POST)]

    public OperationResult MyFriendlyMethod(int id, Customer customer)

    {

        return new OperationResult.Modified { ResponseResource = customer };

    }

}

If you want to have a better control of the Http status code, as it is shown in the code above, you can also return an instance of OperationResult.

Codecs

As you can see, the handlers have not been wired to any content type at this point. Serializing/Deserializing a resource instance into an specific representation is responsibility of the codecs. Some codecs are provided out of the box in OR, for example, Json, Xml, Html or Form-Url-Encoded data.

A codec generally implement two interfaces, IMediaTypeReader (for deserializing content) and IMediaTypeWriter(for serializing). The following code shows the implementation of the Json codec,

[MediaType("application/json;q=0.5", "json")]

public class JsonDataContractCodec : IMediaTypeReader, IMediaTypeWriter

{

    public object Configuration { get; set; }

    public object ReadFrom(IHttpEntity request, System.Type destinationType, string paramName)

    {

        DataContractJsonSerializer serializer = new DataContractJsonSerializer(destinationType);

        return serializer.ReadObject(request.Stream);

    }

    public void WriteTo(object entity, IHttpEntity response, string[] paramneters)

    {

        if (entity == null)

            return;

        DataContractJsonSerializer serializer = new DataContractJsonSerializer(entity.GetType());

        serializer.WriteObject(response.Stream, entity);

    }

}

Putting Handlers and Codecs together

By means of a fluent configuration, we can later wire up an URI with the corresponding handler and one or more codecs according to the content-types that the service should support.

ConfigureServer(() => ResourceSpace.Has.ResourcesOfType<Customer>()

                          .AtUri("/customer/{id}")

                          .HandledBy<CustomerHandler>()

                          .AndTranscodedBy<OpenRasta.Codecs.JsonDataContractCodec>()

                          .AndBy<OpenRasta.Codecs.XmlSerializerCodec>());

This is one of the big differences with the ASP.NET MVC or the Web Programming Model in WCF.

In the MVC, the supported content types are inherently tied to the ActionResult returned by the controller action. Therefore, the action implementation must be modified in order to support new content types.  Or a more specialized implementation of an ActionResult is required, which has to be smart enough to accommodate these changes.

Same thing happens with WCF, you have to either decorate the service operation with the supported content-type (Only Json or Pox supported today) or return a Message/Stream instance from the operation and write the resource representation yourself in the operation implementation. As I said, only Json/Pox are supported today, and adding new content types is something complicated to do. You basically need to write a custom IDispatchMessageFormatter extension, and a custom WebServiceHost to replace the formatter provided out of the box. (This is the approach taken in the WCF REST Starter kit for supporting form-url-encoded data).

Pipeline Contributors

Let’s go back to OpenRasta for a moment, “Handlers” and “Codecs” are not the only supported extensibility points in this framework. All the processing of incoming/outgoing messages is performed in a pipeline that contains contributors or filters. A pipeline contributor perform simple tasks such as initializing the security context, routing the messages or processing exceptions to name a few. You can write your own contributors, or customize the pipeline to support different configurations or scenarios

More information about OpenRasta 

You can find more information about this framework in the Sebastien’s blog. The current project status is also available here.

Many of the features available out of the box today in the ASP.NET MVC framework are only intended to develop web applications using REST principles. There is not support for accepting incoming messages encoded as JSON or plain old XML (POX), or even support for returning POX from a controller action. Only form-urlencoded data is accepted by default for incoming messages, and JSON/HTML (with support of the view engines) for outgoing messages in controller actions.

However, thanks to the different extensibility points that the MVC provides for hooking up custom code, supporting different scenarios for RESTful services tend to be something really easy to implement.

In this framework, we basically have two extensibility points that deserve some attention, Action Filters and Action Results.

Action filters intercept messages before they are dispatched to the controller action (or operation), and just after the operation returns a result. They are basically equivalent to the Dispatch Message Interceptors in WCF, or the new Message Interceptors in the WCF REST Starter kit (although they work more at a deeper level in the WCF processing pipeline).

Action results know how to serialize and write an object (the controller action result) into the response stream. Since they also have access to the Response object, additional work can be done there to manipulate some response settings or add output headers.

The framework also support Model Binders, which basically knows how to create an object representing the model expected by the controller action from some scalar values. Those scalar values are parsed from the incoming message (encoded as form-urlencoded), and then passed to the binder. However, they do not seem to add any value for implementing RESTful services with support for JSON or XML.

Omar Al Zabir has already written an nice post on how to implement RESTful services with the ASP.NET MVC that speak JSON and XML using action filters and action results.

ATOM and other syndication formats can also be handled as XML. For this, the Web Programming Model in WCF comes with a couple of classes, Rss20FeedFormatter and Atom10FeedFormator, which are Data Contracts and also IXmlSerializable classes. Therefore, if your operation returns an instance of any of these classes, the filters created by Omar would address this scenario as well. Regarding Conditional get support, you will have to implement it in the action itself or a custom filter. (You will have to do the same thing if you decide to go with the WCF Web Programming Model).

Caching is another feature that you might want to use at the moment of developing RESTful services. Fortunately, the MVC also comes with an special action filter “OutputCache” that was built on top the ASP.NET cache, so it provides the same caching capabilities that you may use for normal ASP.NET pages.

Aqui pueden encontrar el material de la prestacion que di en el dia de hoy acerca de construccion de web services con ASP.NET y WCF en Visual Studio 2008.

More Posts Next page »