Fault Contract support in WSCF.blue

by Alex Meyer-Gleaves 31 May 2010 - 12:23 AM

Adding support for fault contracts to WSCF.blue has been on my TODO list for quite a while now. It was left behind when the port to WCF was done because ASMX did not have proper support for fault contracts so it was never actually part of WSCF.classic. Back in the old ASMX days you had to manually set the Detail property in the SoapException yourself and then add the fault details to the WSDL by hand.

In WCF your fault messages are declared on your operation using the FaultContractAttribute. When using WSCF.blue you could manually add the fault details to your WSDL and the appropriate FaultContractAttribute would be added to the generated service interface code. The problem was that if you edited your WSDL in the wizard the manually added fault details would be lost. Introducing a manual step like that into your process is something that we all want to avoid. Well, you no longer need to worry about that, because I have now added support for fault contracts to WSCF.blue.

Defining fault messages in your WSDL can be a little different to defining your input and output messages. For example, you can have multiple fault messages for a single operation and the same fault message is often reused for different operations. I decided that the message mapping page of the WSDL Wizard would be a reasonable place to put the configuration for your fault contract.

When you select an operation in the tree control a link label is displayed in the properties pane. Clicking the link will add a new fault message to the operation.

Operation Properties

When you select the fault message in the tree control you can then select a type from your schema to be used as the message body. You must provide a name for the message and that name must be unique to the operation. It does not have to be unique to the entire contract though. This means that you can reuse the same message name for a different operation and only a single message will be added to the WSDL. There is also a link label that allows you to remove the fault message if required.

Fault Message Properties

Lets use the fault message being configured in the screen capture above as an example of how this fits together in regards to the XSD and WSDL. The type for the fault in the XSD is called customFault and is an explicitly named complexType.

<xs:complexType name="customFault">
  <xs:sequence>
    <xs:element name="errorCode" type="xs:string"/>
    <xs:element name="message" type="xs:string"/>
    <xs:element maxOccurs="unbounded" minOccurs="0" name="messages" type="xs:string" />
  </xs:sequence>
</xs:complexType>

The message is then defined as an element with the type set to the customFault type. Do not create your fault type as an anonymous type definition directly under the element for the message. Doing so will result in an error about a missing data type during code generation.

<xs:element name="customFault" type="import:customFault" />

When the type and message schemas are run through the WSDL Wizard, and the fault message is added as shown in the screen capture above, the resulting WSDL will have a new message defined as follows.

<message name="customFaultMessage">
  <wsdl:documentation xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" />
  <part name="fault" element="import0:customFault" />
</message>

The portType will then have the fault defined for the operation.

<operation name="getRestaurants">
  <wsdl:documentation xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" />
  <input message="tns:getRestaurantsIn" />
  <output message="tns:getRestaurantsOut" />
  <fault name="customFaultMessage" message="tns:customFaultMessage" />
</operation>

The binding will also have the fault defined for the matching operation.

<operation name="getRestaurants">
  <soap:operation soapAction="http://www.thinktecture.com:getRestaurantsIn" style="document" />
  <input>
    <soap:body use="literal" />
  </input>
  <output>
    <soap:body use="literal" />
  </output>
  <fault name="customFaultMessage">
    <soap:fault use="literal" name="customFaultMessage" namespace="" />
  </fault>
</operation>

Now when you generate your service code a FaultContractAttribute will be applied to the method on your service interface that declares the operation. Note that the FaultContractAttribute specifies customFault as the type to be used for the message body.

[System.ServiceModel.OperationContractAttribute(Action="http://www.foo.com/:getRestaurantsIn", ReplyAction="*")]
[System.ServiceModel.FaultContractAttribute(typeof(customFault), Action="http://www.foo.com/:getRestaurantsIn", Name="customFault", Namespace="urn:thinktecture-com:demos:restaurantservice:messages:v1")]
[System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults=true)]
getRestaurantsResponse getRestaurants(getRestaurantsRequest request);

There have been a number of requests for fault contract support on the CodePlex forum and I hope that you too will find this helpful. A new V1.0.9 update release is now available on CodePlex for download. Please put this new feature through its paces and report any problems you find on the discussion forum.

Tags: ,

Categories: Web Services | WSCF | Development Tools

Making Self-Hosting with Autofac WCF Integration easier

by Alex Meyer-Gleaves 16 May 2010 - 1:48 AM

Thinking about the sample I recently posted for shelf-hosting WCF Services with the Autofac WCF Integration, I decided that the boilerplate code for configuring the Service Behavior could be moved into an extension method on the ServiceHost instead. I have checked in some code that will extend ServiceHostBase with a new method called AddDependencyInjectionBehavior. There are two overloads of the method, one that takes a generic argument for the service contract type, and another that allows you to provide a Type for the service contract in case you are configuring your WCF Services in some sort of latebound manner. Both overloads of the method require an IContainer instance.

host.AddDependencyInjectionBehavior<IEchoService>(container);
host.AddDependencyInjectionBehavior(typeof(IEchoService), container);

As you can see from the updated sample below, the extension method makes the code considerably more concise, and will save you from having to write your own helper method that can be reused with your different WCF Services.

ContainerBuilder builder = new ContainerBuilder();
builder.Register(c => new Logger()).As<ILogger>();
builder.Register(c => new EchoService(c.Resolve<ILogger>())).As<IEchoService>();

using (IContainer container = builder.Build())
{
    Uri address = new Uri("http://localhost:8080/EchoService");
    ServiceHost host = new ServiceHost(typeof(EchoService), address);

    host.AddServiceEndpoint(typeof(IEchoService), new BasicHttpBinding(), string.Empty);

    host.AddDependencyInjectionBehavior<IEchoService>(container);

    host.Description.Behaviors.Add(new ServiceMetadataBehavior {HttpGetEnabled = true, HttpGetUrl = address});
    host.Open();
    
    Console.WriteLine("The host has been opened.");
    Console.ReadLine();

    host.Close();
    Environment.Exit(0);
}

The extension method will be available in the next release of Autofac. If you want to try it out without grabbing the latest Autofac source, the code below should give you a feel for how it works. You do not need to provide the service implementation type to the extension method because it can be retrieved from the ServiceHost instance. The Type instance that you provide in the ServiceHost constructor surfaces as the ServiceHost.Description.ServiceType property and can be used directly in the extension method.

public static class ServiceHostExtensions
{
    public static void AddDependencyInjectionBehavior<T>(this ServiceHostBase serviceHost, IContainer container)
    {
        AddDependencyInjectionBehavior(serviceHost, typeof(T), container);
    }

    public static void AddDependencyInjectionBehavior(this ServiceHostBase serviceHost, Type contractType, IContainer container)
    {
        IComponentRegistration registration;
        if (!container.ComponentRegistry.TryGetRegistration(new TypedService(contractType), out registration))
        {
            string message = string.Format("The service contract type '{0}' has not been registered in the container.", contractType.FullName);
            throw new ArgumentException(message);
        }

        AutofacDependencyInjectionServiceBehavior behavior = new AutofacDependencyInjectionServiceBehavior(
            container, serviceHost.Description.ServiceType, registration);
        serviceHost.Description.Behaviors.Add(behavior);
    }
}

Nothing fancy here but that should make self-hosting a little easier.

Tags: ,

Categories: Autofac | Web Services

Self-Hosting WCF Services with the Autofac WCF Integration

by Alex Meyer-Gleaves 7 May 2010 - 12:14 AM

A question came up recently in the Autofac group about how to use the WCF Integration when self-hosting WCF Services. This post provides a quick demonstration of how to handle the self-hosting scenario and should be enough to get you started. The example is a rather unimaginative web service that echoes back a message.

First declare the interface and implementation for a logger that the WCF Service will take as a dependency in its constructor. This is a simple logger that will log the message sent to the WCF Service out to the console.

public interface ILogger
{
    void Write(string message);
}

public class Logger : ILogger
{
    public void Write(string message)
    {
        Console.WriteLine(message);
    }
}

Next you need to define the contract and implementation for the WCF Service. Nothing interesting here other than our dependency being requested through the constructor of the WCF Service implementation.

[ServiceContract]
public interface IEchoService
{
    [OperationContract]
    string Echo(string message);
}

public class EchoService : IEchoService
{
    private readonly ILogger _logger;

    public EchoService(ILogger logger)
    {
        _logger = logger;
    }

    public string Echo(string message)
    {
        _logger.Write(message);
        return message;
    }
}

Now we can create a Console Application that will configure the container and host our WCF Service.

ContainerBuilder builder = new ContainerBuilder();
builder.Register(c => new Logger()).As<ILogger>();
builder.Register(c => new EchoService(c.Resolve<ILogger>())).As<IEchoService>();

using (IContainer container = builder.Build())
{
    Uri address = new Uri("http://localhost:8080/EchoService");
    ServiceHost host = new ServiceHost(typeof(EchoService), address);
    host.AddServiceEndpoint(typeof(IEchoService), new BasicHttpBinding(), string.Empty);

    IComponentRegistration registration;
    if (!container.ComponentRegistry.TryGetRegistration(new TypedService(typeof(IEchoService)), out registration))
    {
        Console.WriteLine("The service contract has not been registered in the container.");
        Console.ReadLine();
        Environment.Exit(-1);
    }

    host.Description.Behaviors.Add(new AutofacDependencyInjectionServiceBehavior(container, typeof(EchoService), registration));
    host.Description.Behaviors.Add(new ServiceMetadataBehavior {HttpGetEnabled = true, HttpGetUrl = address});
    host.Open();
    
    Console.WriteLine("The host has been opened.");
    Console.ReadLine();

    host.Close();
    Environment.Exit(0);
}

Here we have added an IServiceBehavior called AutofacDependencyInjectionServiceBehavior that will add a custom IInstanceProvider to the DispatchRuntime of each endpoint’s EndpointDispatcher. That is a bit of a mouth full but basically means that Autofac will use the WCF extensibility points to provide WCF Service instances that have their dependencies injected.

In this example the WCF Service is exposed on an endpoint that uses the BasicHttpBinding but you can use any type of endpoint that you like. I have added a ServiceMetadataBehavior in this example that exposes the WSDL for the WCF Service at http://localhost:8080/EchoService?wsdl. You can use this address to create a client proxy and send test messages that are hopefully more creative than my example.

Tags: ,

Categories: Autofac | Web Services

WSCF.blue Roadmap

by Alex Meyer-Gleaves 6 May 2010 - 12:00 AM

image The WSCF.blue team has been discussing the features we should include in the next release. Benjy has done a great job summarising the current roadmap on his blog and is inviting feedback. You might feel that important features are missing, or perhaps that a particular feature is a bad idea, and would take the tool in the wrong direction. I decided that I would share what features are important to me, and put out for consideration and feedback some concerns I have with particular features. It is worth noting at this point that this is not an official roadmap, and is really just a summary of the ideas that we have been throwing around.

Having used WSCF.blue in a team environment, I would certainly put having the ability to permanently persist the settings for a web service in a way that makes them easy to share at the top of my list. Perhaps some sort of project structure that keeps your WDSL and XSD files along with your preferences altogether. There are a number of different options that can be applied when generating your web service code, and it is important that this step be repeated consistently, regardless of the developers familiarity with that particular web service. In regards to the actual options, I would also like to see support for WS-Addressing and fault contracts in the WSDL generation process. Adding these into the contract manually becomes another step that could be forgotten.

The issues noted about T4 templates are primarily concerns that I raised with the team. You get great flexibility with such a technology but it does come at a cost. These templates are not immediately approachable to all developers, especially when you are dealing with a complex model with many possible combinations. There are tools that make developing templates a more pleasant experience, but the mixing of static and dynamic content in such a manner still makes it fairly easy to introduce errors. I worry that it would become difficult to determine if a problem exists within the codebase or has been introduced in a customised template. Being an open source project there is only so much time that can be dedicated to support, so making things simple and reliable feels important. There is of course also the issue of upgrading templates, which forces users to migrate their customisations each time changes are made to the original.

Microsoft has released Feature Builder and it looks like it would be a very good fit for a tool like WSCF.blue. It certainly appears to be a considerable improvement over the Guidance Automation Toolkit (enough said). I would think that if we chose Feature Builder as the primary user experience, we would want to write an Ultimate Feature Extension that takes advantage of the modeling and visualization features that exist in Visual Studio 2010 Ultimate Edition. This is the point that you can start to do some really interesting things with Feature Builder. The problem is of course the requirement to have the most recent and expensive version of Visual Studio. My concern here is that we would make the tool inaccessible to a number of developers, and we really want as many people as possible to use the tool and embrace the contract-first approach.

There are a lot of great ideas on the roadmap and some really interesting technology choices to be made. I would be glad to hear your thoughts on any of these issues and the roadmap in general.

Tags: ,

Categories: Web Services | WSCF | Development Tools

MockingBird v2.0 Release Candidate Available

by Alex Meyer-Gleaves 21 March 2010 - 1:41 AM

Santosh Benjamin recently announced that a Release Candidate of MockBird v2.0 is now available for download on CodePlex. In case you are not yet familiar with MockingBird, it is a tool that allows you to mock web services through configurable message interception. Below is a high level overview of the system.

MockingBird High Level Overview

If this sounds like something you would be interested in, be sure to test it out and provide some feedback.

Tags:

Categories: Web Services

WSCF.blue now supports Visual Studio 2010 RC

by Alex Meyer-Gleaves 24 February 2010 - 12:56 AM

image There is another WSCF.blue update (V1.0.7) available for download on CodePlex. This update adds support for Visual Studio 2010 RC in addition to Visual Studio 2008. Please note that Visual Studio 2010 Beta 2 is not supported.

All features should work exactly the same way in both versions of Visual Studio. If you have any problems please jump onto the Issue Tracker and let us know.

I would also love to hear more about what features you would like to see in upcoming versions of WSCF.blue. If you have any thoughts please contact me or simply start a thread in the Discussions forum. Your feedback is always welcome.

Tags: ,

Categories: Web Services | WSCF

WSCF.blue V1.0.6 Update

by Alex Meyer-Gleaves 18 February 2010 - 1:20 AM

There is now a V1.0.6 update for WSCF.blue that includes fixes for a number of bugs that have been reported since the V1.0.5 release. It has taken some large and complex contracts to uncover some of the more obscure bugs. Below is a list of the bugs that have been fixed:

  • The data contract type filter was not including all the required types in some complex contracts.
  • When adjusting the casing of enumeration members references in DefaultValue attributes and constructors were not being updated.
  • When using the List<T> option along with the Public properties option the backing field used for properties was sometimes left as an array instead of a generic list.
  • When using the List<T> option along with the Public properties option the backing field used for properties with an XmlChoiceIdentifier attribute was converted to a generic list instead of being left as an array to match the property.
  • Fixed an Adjust casing bug related to enumeration values that cannot be used as valid property names. The XmlEnumAttribute was being set to the generic ItemX property name instead of being left with the value from the original enumeration.

If you have any problems with the update please let us know through the Issue Tracker. Thanks to everyone who has reported bugs.

Tags: ,

Categories: WSCF | Web Services

More than 1000 downloads for WSCF.blue V1

by Alex Meyer-Gleaves 5 January 2010 - 12:41 AM

On the last day of September in 2009 we released the first version of WSCF.blue on CodePlex. I was very pleased to see that there has now been more than 1000 downloads of the V1 release. Congratulations to the team and thank you to everyone who has downloaded WSCF.blue. It is great to see that interest in contract-fist development is still alive and well. Of course, Christian and Buddhike did a great job of spreading the word with their excellent MSDN article.

image

Now that everyone is back from holidays and feeling refreshed there is no doubt work will continue on the next version. We all have plenty of ideas for the features we would like to see, but what we would really like is feedback from the community on what you want. If you have ideas on what you would like to see in future versions of WSCF.blue please jump onto the forum and let us know.

Tags:

Categories: WSCF | Web Services | Development Tools

Would you become a signatory of the SOA Manifesto?

by Alex Meyer-Gleaves 20 November 2009 - 11:12 PM

Most developers have heard of the Agile Manifesto, but did you know there is also a SOA Manifesto? Like the Agile Manifesto, and perhaps even more so, I am sure it will be wide open to interpretation and will spark some level of debate. There is already a SOA Manifesto Dialog site dedicated to discussion of the manifesto, and a poll that it hosts suggests that opinion is indeed varied. I have embedded the same poll below if you would like to voice your opinion right now.

I am just happy to see some activity taking place within the SOA community, and for SOA to be getting some form of press once again. SOA has provided a great deal of benefit to the many organisations that have embraced it, and I believe that fact should be recognised. If you too believe in the benefits that SOA delivers you should head on over to the site, and if you agree with what is written become a signatory to the manifesto.

Tags:

Categories: Web Services

Contract-First article on MSDN

by Alex Meyer-Gleaves 4 October 2009 - 12:44 PM

Congratulations to Christian and Buddhike for their excellent MSDN article: Schema-based Development with Windows Communication Foundation. If you are new to contract-first web service development, or even if you have been practicing it for a while, I am sure you will really enjoy reading this article. It is great to see an article on MSDN that is focused on contract-first and how it can be achieved with WCF. Of course, there is a section dedicated to the WSCF.blue Visual Studio 2008 Add-in.

The diagram below was created for the article, and Christian has also put it on the WSCF.blue homepage on CodePlex.

The schema-first approach has five discrete steps.

I really like this diagram, it paints a picture that is very clear and easy to understand. It shows that there is a sequence of steps that are undertaken when doing contract-first development, and highlights that this entire sequence becomes an iterative process. Well done guys!

Tags: ,

Categories: Web Services | WSCF

About the author

Alex Meyer-Gleaves I'm a software developer living in Australia (that island like continent in the southern hemisphere). I love Microsoft .NET and C#. I hate early mornings, slow drivers and Lotus Notes.

Google Reader Clips

SpringWidgets
RSS Reader
This widget is the staple of our platform. Read all your feeds right here with thisone widget - Supported feeds are OPML, RSS, RDF, ATOM. Watch your favorite Podcastin the embedded Video Player on the Desktop or publish your own video playlist toyour site for others to view!

Recent Comments

Comment RSS

Links

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in  anyway.

© Copyright 2008