Submit to Reddit      
  

The ChannelAdam Nancy SOAP Library

Overview

The ChannelAdam Nancy SOAP Library is an open source (Apache License 2.0) .NET code library that provides functionality for working with SOAP 1.1 and SOAP 1.2 payloads in the lightweight Nancy web framework.

This library builds upon the foundational ChannelAdam Nancy Library and is complemented by:


Getting Started

NuGet Package Installation

To install the ChannelAdam.Nancy.Soap NuGet package run the following command in the Package Manager Console:

PM> Install-Package ChannelAdam.Nancy.Soap


Show Me Some Code!

Below are some simple code examples. See the reference in the next section for information on more advanced usage.

Example Hello World SOAP Nancy Module

Below is a simple example of a Nancy Module that defines a handler for a SOAP action.

public class HelloWorldSoapNancyModule : NancyModule
{
    public HelloWorldSoapNancyModule(INancySoapAdapter soapAdapter)
    {
        const string helloWorldSoapServiceRoutePattern = "/HelloWorldSoap11Service";

        // Define the route pattern in Nancy
        DefineSoapRoute(helloWorldSoapServiceRoutePattern, soapAdapter);

        // Register SOAP action handlers for that route pattern
        soapAdapter.RegisterSoapActionHandler(helloWorldSoapServiceRoutePattern, "urn:HelloWorldSoap11Service#HelloWorldSoapAction",
            (request, routeArgs) =>
                Soap11NancyResponseFactory.Create(
                    SoapBuilder.CreateSoap11Envelope().WithBody.AddEntry("<root>Hello SOAP World!</root>"),
                    HttpStatusCode.OK));

        // And register more SOAP action handlers for the same route pattern:
        // soapAdapter.RegisterSoapActionHandler(helloWorldSoapServiceRoutePattern, "urn:HelloWorldSoap11Service#AnotherSoapAction", ...
    }

    private void DefineSoapRoute(string routePattern, INancySoapAdapter soapAdapter)
    {
        Post[routePattern] = args => soapAdapter.ProcessRequest(routePattern, base.Request, args);
    }
}

There are three important things going on here:

  1. The ChannelAdam.Nancy.Soap.INancySoapAdapter is injected into the constructor of the Nancy Module class. Nancy's default bootstrapper will automatically resolve the INancySoapAdapter soapAdapter parameter in the constructor, so you don't need to be concerned about the constructor injection.

  2. As one normally would do, the route is defined. For a SOAP action, typically that would be done with a HTTP Post. Here is where it gets interesting. For a given route pattern, the action argument to specify is the INancySoapAdapter.ProcessRequest method. This ProcessRequest method on the SOAP Adapter conveniently extracts the SOAP action from either the HTTP header or the SOAP header and then dispatches the request to the corresponding SOAP action handler method that has been registered with it (see the next point).

  3. A SOAP action handler for the same route pattern is registered with the SOAP Adapter. We use the Soap11NancyResponseFactory.Create() method to convert the result of the SoapBuilder (or any string) into a Nancy Response with the appropriate content type for the version of SOAP you are using. Of course, there is also a Soap12NancyResponseFactory helper class for SOAP 1.2 responses.


Example of Self-Hosting Nancy in an Automated Test

Sometimes you want to mock out your actual SOAP services so you can perform Unit Testing instead of Integration Testing. With the ChannelAdam Nancy SOAP Adapter, it is possible to self-host Nancy in the same process as your test case, and just like a mock object, configure it to respond with a specific payload for the current Unit Test.

Below is some dirty automated test code (meant only for this purpose of demonstrating the simplest usage).

Note: I highly recommend following Behaviour-Driven Development practices and the usage of SpecFlow for automated testing.

Step 1 - Identify the Routes and SOAP Actions

The first step is to identify the routes patterns and SOAP actions. Maybe you have these already defined in some constant classes somewhere and if so that's perfect. For the purpose of this example though, I am putting them into the following static classes.

public static class TestCaseRoutes
{
    public static readonly string MySoap11Service = "/MySoap11Service";
}

public static class TestCaseSoapActions
{
    public static readonly string MySoap11ServiceTestAction = "urn:MySoap11Service#TestAction";
}
Step 2 - Define a Nancy Module

The next step for an automated test is to create a Nancy Module and define a route.

Unlike the example Hello World Nancy Module above, the difference for an automated test is that within the Nancy Module you would not register the SOAP action handler with the SOAP Adapter (as that will be done later in the test code). The only thing you need to do in the Nancy Module is define the routes.

public class TestCaseNancyModule : NancyModule
{
    public TestCaseNancyModule(INancySoapAdapter soapAdapter)
    {
        DefineSoapRoute(TestCaseRoutes.MySoap11Service, soapAdapter);
    }

    private void DefineSoapRoute(string routePattern, INancySoapAdapter soapAdapter)
    {
        Post[routePattern] = args => soapAdapter.ProcessRequest(routePattern, base.Request, args);
    }
}
Step 3 - Write the Test Code

Finally the last step is to write the test code.

private const string NancyBaseUrl = "http://localhost:8087";

private NancySoapAdapter nancySoapAdapter;
private NancyHost nancyHost;

private string expectedSoapBodyEntryXml;

public void SimpleDirtyTestCode()
{
    //------------
    // Set up
    //------------

    // Self host Nancy
    this.nancySoapAdapter = new NancySoapAdapter();
    this.nancyHost = NancySelfHostFactory.CreateAndStartNancyHostInBackgroundThread(
        new NancySoapAdapterBootstrapper(this.nancySoapAdapter), 
        new Uri(NancyBaseUrl));

    //------------
    // Arrange
    //------------
    this.expectedSoapBodyEntryXml = "<root>Whatever you need for this test</root>";

    // Register SOAP action handler for the route pattern
    soapAdapter.RegisterSoapActionHandler(TestCaseRoutes.MySoap11Service, TestCaseSoapActions.MySoap11ServiceTestAction,
        (request, routeArgs) =>
        {
            // Return a Nancy Response with whatever this specific test case requires...
            // A SOAP body entry or Soap11NancyResponseFactory.CreateFault()... 
            return Soap11NancyResponseFactory.Create(
                SoapBuilder.CreateSoap11Envelope().WithBody.AddEntry(this.expectedSoapBodyEntryXml),
                HttpStatusCode.OK);
        });

    //------------
    // Act
    //------------
    /// TODO - Invoke your System Under Test that will call the Nancy route with the specified SOAP action

    //------------
    // Assert
    //------------
    // TODO - assert the actual response equals this.expectedSoapBodyEntryXml
    //      - or that a FaultException occurred...

    //------------
    // Tear Down
    //------------
    this.nancyHost.Stop();
}

The important things to understand are:

  • With the help of the ChannelAdam.Nancy.SelfHosting.NancySelfHostingFactory class, we are self-hosting Nancy in the same process as the test case. Because of this, we specifically create and start it in a background thread so that if the main thread of the test case performs a HTTP request to the route, then everything will respond and be processed as expected.

  • We explicitly create the NancySoapAdapter in the test case and bootstrap it with the NancySoapAdapterBootstrapper into the factory method that creates and starts Nancy. This ensures that the Nancy Module constructor receives the SOAP Adapter instance that we created.

  • Using the NancySoapAdapter, we then register a SOAP action handler specifically returning the response required by the test case.


Reference

NancySoapAdapter & INancySoapAdapter

The ChannelAdam.Nancy.Soap.NancySoapAdapter class which implements the ChannelAdam.Nancy.Soap.Abstractions.INancySoapAdapter interface makes all the magic happen for adapting SOAP payloads to work easily in Nancy.

There are four methods in the interface:

  • Response ProcessRequest(string routePattern, Request request) - this is the action to specify in the Nancy route definition to dispatch the HTTP request to the registered handler for the SOAP action named in the HTTP request header or SOAP header.

  • Response ProcessRequest(string routePattern, Request request, dynamic requestRouteArgs) - this is the action to specify in the Nancy route definition to dispatch the HTTP request to the registered handler for the SOAP action named in the HTTP request header or SOAP header. This overload allows the requestRouteArgs from the route pattern to be provided.

  • void RegisterSoapActionHandler(string routePattern, string soapAction, NancyRequestHandler handler) - registers a handler for the specified route pattern and SOAP action.

  • Request TryWaitForRequest(string routePattern, string soapAction, int retryCount, TimeSpan sleepDuration) - Waits for a specified amount of time for a HTTP request to be received on the specified route with the given SOAP action.


NancySoapAdapterBootstrapper

The NancySoapAdapterBootstrapper is a custom bootstrapper for Nancy.

Normally you don't need to be concerned with this, but it is especially useful in automated tests.

There are two constructors:

  • public NancySoapAdapterBootstrapper() - which will create a NancySoapAdapter instance for you.

  • public NancySoapAdapterBootstrapper(INancySoapAdapter soapAdapter) - which allows you to specify your own instance of the NancySoapAdapter (which is especially useful in automated tests).


Soap11NancyResponseFactory

The Soap11NancyResponseFactory static class allows you to create a Nancy Response with the correct content type for SOAP 1.1.

There are five methods on the static class:

  • public static Response Create(ISoap11EnvelopeBuilder envelopeBuilder, HttpStatusCode httpStatusCode) - to create a Nancy Response from the specified ISoap11EnvelopeBuilder with the correct content type for SOAP 1.1 and with the specified HttpStatusCode.

  • public static Response Create(XContainer soap11Envelope, HttpStatusCode httpStatusCode) - to create a Nancy Response from the specified SOAP 1.1 envelope in the XContainer with the correct content type for SOAP 1.1 and with the specified HttpStatusCode.

  • public static Response Create(string soap11EnvelopeXml, HttpStatusCode httpStatusCode) - to create a Nancy Response from the specified SOAP 1.1 envelope XML string with the correct content type for SOAP 1.1 and with the specified HttpStatusCode.

  • public static Response CreateFault(ISoap11EnvelopeBuilder envelopeBuilder) - to create a Nancy Response with a SOAP 1.1 fault, as specified by the ISoap11EnvelopeBuilder, with an HttpStatusCode.InternalServerError.

  • public static Response CreateFault(XContainer envelope) - to create a Nancy Response with a SOAP 1.1 fault, as specified by the SOAP 1.1 envelope in the specified XContainer, with an HttpStatusCode.InternalServerError.


Soap12NancyResponseFactory

The Soap12NancyResponseFactory static class allows you to create a Nancy Response with the correct content type for SOAP 1.2. This is the SOAP 1.2 equivalent of the Soap11NancyResponseFactory.

There are five methods on the static class:

  • public static Response Create(ISoap12EnvelopeBuilder envelopeBuilder, HttpStatusCode httpStatusCode) - to create a Nancy Response from the specified ISoap11EnvelopeBuilder with the correct content type for SOAP 1.2 and with the specified HttpStatusCode.

  • public static Response Create(XContainer soap12Envelope, HttpStatusCode httpStatusCode) - to create a Nancy Response from the specified SOAP 1.2 envelope in the XContainer with the correct content type for SOAP 1.2 and with the specified HttpStatusCode.

  • public static Response Create(string soap12EnvelopeXml, HttpStatusCode httpStatusCode) - to create a Nancy Response from the specified SOAP 1.2 envelope XML string with the correct content type for SOAP 1.2 and with the specified HttpStatusCode.

  • public static Response CreateFault(ISoap12EnvelopeBuilder envelopeBuilder) - to create a Nancy Response with a SOAP 1.2 fault, as specified by the ISoap11EnvelopeBuilder, with an HttpStatusCode.InternalServerError.

  • public static Response CreateFault(XContainer envelope) - to create a Nancy Response with a SOAP 1.2 fault, as specified by the SOAP 1.2 envelope in the specified XContainer, with an HttpStatusCode.InternalServerError.


SoapNancyRequestHelper

The SoapNancyRequestHelper static class provides helpful functionality that operates on a Nancy Request.

There is one method on the static class:

  • public static string GetSoapAction(Request request) - to retrieve the SOAP action from either the HTTP header or the SOAP envelope header. The HTTP header takes precedence.

This functionality is also surfaced as an extension method on the Nancy Request class for which you will need a using statement for ChannelAdam.Nancy.Soap.




comments powered by Disqus