Friday, June 29, 2012

Combo RESTful WCF with Windows Service Hosting and Dynamic Response Format

The Goal
I have been working through the plausibility of multipurpose WCF services that are hosted in a windows hosting environment.  As part of my research, I wanted to prove that you could host a single service as a standard service to be consumed by a client proxy and scale it out from there to webHTTP and RESTful behavior.  The biggest goal I had was to make the service dynamically reply in the same format in which it was consumed without having a drawn out implementation to handle the messaging.

The Project
After some reading and messing around I have completed the following project which does exactly what I had hoped.  This single WCF implementation will allow for a straight service call, a RESTful call and respond dynamically with xml or json to the REST query based on the content type value of the request header.  All while being hosted in a windows service that can be dynamically deployed.  I came up with a very simple project that allows for interaction with a listing of albums.  The example is simple, but the devil of this was not in the actual data elements, so I flagged the scalability of that as irrelevant to the goal of illustrating the mechanism.

The Services
I created a basic WCF service to perform CRUD on my album repository. You will notice the service decorations on the interface indicating both an operation contract and a WebInvoke/WebGet behavior and template.


[ServiceContract(Name = "AlbumContract", 
     Namespace = "RESTCombo.Services", 
     SessionMode = SessionMode.Allowed)]
public interface IAlbumSvc:IMetadataExchange
{
    [OperationContract]
    [WebGet(UriTemplate = "/Albums/{id}"), 
        Description("Returns the album with the passed ID")]
    Album GetAlbum(String id);
 
    [OperationContract]
    [WebGet(UriTemplate = "/Albums"), 
        Description("Returns the entire list of albums")]
    List<Album> GetAlbums();
 
    [OperationContract]
    [WebInvoke(Method = "POST", UriTemplate = "/Albums"), 
         Description("Adds a new album to list of albums")]
    void AddAlbum(Album album);
 
    [OperationContract]
    [WebInvoke(Method = "PUT", UriTemplate = "/Albums"), 
         Description("Updates an existing album")]
    void UpdateAlbum(Album album);
 
    [OperationContract]
    [WebInvoke(Method = "DELETE", UriTemplate = "/Albums/{id}"), 
         Description("Removes an album from list of albums")]
    void DeleteAlbum(String id);
}
 
The WebGet and WebInoke decoration allows the services to respond as a RESTful WCF service based on the URI template.  The service implementation should be decorated as follows:


[ServiceBehavior(Name = "RESTCombo.Services.AlbumSvc", 
    ConcurrencyMode = ConcurrencyMode.Single, 
    InstanceContextMode = InstanceContextMode.Single,
    IncludeExceptionDetailInFaults = true)]    
[AspNetCompatibilityRequirements(
    RequirementsMode=AspNetCompatibilityRequirementsMode.Allowed)]
public class AlbumSvc : IAlbumSvc

I'm going to skip posting the implementation of the services themselves as they are actually irrelevant to the discussion.  The entire project is attached at the end of the post if you would like to review the code.

The Configuration
While most of the configuration is fairly straight-forward, there are a couple of items worth pointing out.  Notice the multiple bindings for the single service.  Each must respond on its own port.  You can have as many bindings as needed up to one per protocol.  The webHttp endpoint behavior is vital to this mechanism.  helpEnabled allows users to use the '/help' switch at the end of a query to get a service overview page as shown here.


defaultOutgoingResponseFormat is our selection for the default response to a webHttp request. automaticFormatSelectionEnabled allows the response to dynamically detect the request format and respond in kind.

<?xml version="1.0"?>
<configuration>
  
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0"/>
  </startup>
  <system.serviceModel>
    <services>
      <service name="RESTCombo.Services.AlbumSvc">
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8080/AlbumSvc/" />
            <add baseAddress="net.tcp://localhost:2122" />
          </baseAddresses>
        </host>
        <endpoint  binding="webHttpBinding" contract="RESTCombo.Services.IAlbumSvc"
                  bindingConfiguration="RESTBindingConfiguration" 
                   behaviorConfiguration="RESTEndpointBehavior"/>      
        <endpoint address="net.tcp://localhost:2122/AlbumSvc/" binding="netTcpBinding"
                  contract="RESTCombo.Services.IAlbumSvc"/>
      </service>
    </services>    
    <bindings>
     <webHttpBinding>
        <binding name="RESTBindingConfiguration">
          <security mode="None" />          
        </binding>
      </webHttpBinding>      
      <netTcpBinding>
        <binding name="DefaultBinding">
          <security mode="None"/>
        </binding>        
      </netTcpBinding>
    </bindings>
    <behaviors>      
      <endpointBehaviors>
        <behavior name="RESTEndpointBehavior">           
          <webHttp helpEnabled="true" defaultOutgoingResponseFormat="Xml"
                   automaticFormatSelectionEnabled="true"/>
        </behavior>
      </endpointBehaviors>
      
      <serviceBehaviors>                        
        <behavior name="DefaultBehavior">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>       
      </serviceBehaviors>
    </behaviors>  
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" 
                               aspNetCompatibilityEnabled="true" />
  </system.serviceModel>
</configuration>

The Testing
We will just fast-forward through the hosting setup and service implementation.  Now that services are configured, built and running, we can perform the response testing and see how it all comes together.  When browsing to the webHttp base address and invoking the services via RESTful queries, I receive the following responses for the list and single respectively.




Then, to prove the JSON / XML switch, I used a fiddler software to create and review requests and responses.  First, I constructed an XML request and trapped the response.



Then, I constructed a JSON request and trapped the response.




As you can see, the service is responding to me in the request format.  For the client proxy implementation, review the source code attached at the end of the post.  The big victory here is the open and scalable approach to an SOA.  By doing dynamic communication in this manner, we are enabling a service to be consumed in the way that an integrator can best leverage.  This allows us to have a single implementation of intelligence and functionality while allowing any integrating software to choose the manner in which it interacts.  This is very powerful and very scalable and should allow your services to be consumer agnostic and focus strictly on intelligence.  For further review, download the entire project here.

Monday, June 25, 2012

Dynamic Types Using C#


I ran across a scenario the other day for creating a function to perform similar work on similar classes without having to be tightly coupled to any concrete type.  I found a few viable options and will be doing some examples of each to work through the exercise completely.  The first I want to talk through is the use of the dynamic keyword.

In short, using dynamic tells the compiler to ignore types at compile time and instead determine dispatch based on the actual type at run time.  Static binding of types does the exact opposite and performs a dispatch based on the concrete type.  Since code always illustrates these academic discussions more clearly, I created a simple project.  I have two examples of dynamic typing built into this single example.  I created some classes to illustrate a few types that are completely unrelated to each other. I also created a single class that was an example of type inheritance.

public class Account
{
    public String Name { get; set; }
    public Double Balance { get; set; }
    public Int16 AccountType { get; set; }
    public Account()
    {
        Name = "Account";
        Balance = 100.00;
    }
}
 
public class Customer
{
    public String Name { get; set; }
    public Double Balance { get; set; }
    public String CustomerType { get; set; }
    public Customer()
    {
        Name = "Customer";
        Balance = 900.00;
    }
}
 
public class Employee
{
    public String Name { get; set; }
    public Double Balance { get; set; }
    public String Department { get; set; }
    public Employee()
    {
        Name = "Employee";
        Balance = 500.00;
    }
}
 
public class Payable : Account
{
    public Payable()
    {
        Name = "Payable";
        Balance = -100;
    }
}

As you can see, the classes are completely independent of each other, but they have similar members.  Using the dynamic keyword, we can create a function that deals with these types at runtime and interacts with expected members at that time.

static void WriteDynamicObject( dynamic thing)
{
    Console.WriteLine("Name: "+ thing.Name + ", Balance: " + thing.Balance.ToString());
}
 
As long as the types I pass to this function have publicly accessible members named Name and Balance, this code will work with a complete disregard for compilation of any known type.  Next, to illustrate using the dynamic keyword for instructing the runtime to resolve the type regardless of declaration, I created overloaded functions that take a concrete type at each level of inheritance.

static void WriteConcrete(Account thing)
{
    Console.WriteLine("I am an Account Thing");
}
static void WriteConcrete(Payable thing)
{
    Console.WriteLine("I am a Payable Thing");
}

Finally, a simple console application that illustrates how these items work and are either statically or dynamically resolved.  The difference between the 'Concrete' functions is shown by the dynamic keyword telling the runtime to resolve this class at run time regardless of it's declaration.  Also, notice the last item is not even a class at all, but rather a dynamic type declared simply to be passed to this helper function.


static void Main(string[] args)
{
    // call writedynamicobject function for all concrete classes
    Account a = new Account();
    WriteDynamicObject(a);
            
    Employee e = new Employee();
    WriteDynamicObject(e);
            
    Customer c = new Customer();
    WriteDynamicObject(c);
 
    //call function for a concrete class, but resolve type at runtime
    Account p = new Payable();
    WriteConcrete(p);
    WriteConcrete((dynamic)p);
    // dynamically create values and pass as a dynamic type.
    WriteDynamicObject(new {Name="TotallyDynamicNonClass", Balance=250});
 
}
 
The output of this project illustrates how the runtime deals with each of these scenarios.


If you are like me, the first thought you have on using the dynamic typing pattern is along the lines of, "Couldn't you just use an interface or inheritance to accomplish the same thing?"  The answer is yes, assuming you are able to know those types at compile time.  But, there are also times where you can't know the definitions at compile time.  You can't compile the internet, but you can interface with it.  I would be remiss if I didn't get into the downsides of this practice as well.  This can open you up to having a program that is hard to maintain, difficult to debug and unit test and many similar issues. But, guns don't kill people, people with guns do.  Dynamic typing doesn't make code difficult to manage, a programmer does those things with his or her architecture.  This is not a magic bullet and should be used with great caution. The reason for using it is that some problems are inherently dynamic (e.g. web requests).  While you may use reflection for this sort of problem today, you may find dynamic typing a more expressive approach to the same problem.  Simply being dynamic in itself is a compelling argument. Reflection introduces a tightly coupled dependency on a static mechanism.  Dynamic methodologies are intent-based and trust the receiver to act upon the passed intent which creates a scalability unachievable by other means.  The source files are available for download here