Showing posts with label WCF. Show all posts
Showing posts with label WCF. Show all posts

Tuesday, December 15, 2009

Consume RestFul Service as Object using WCF.


As an enterprise software engineer, i deal with disparate systems. I deal with several impedance mismatches between these systems, i built several integration components to glue these systems together. Many of these systems have its domain semantics (They speak different languages ), my daily work life activities is to build abstractions over semantics of different and disparate systems. I am one of those software engineers that believe in domain engineering paradigm , separation of concerns (A dog is a dog not a dogcat) , inversion of control e.t.c I enjoy spending time on a solution to see how it could be done better.My daily work is so challenging that bringing systems together from multiple domain is my strength and i have used aspect orientation to my advantage.

Recently, i entered a problem, we have an application that exposes objects as pure xml , the application supports soap 11 . The soap envelope does not have an action (Simply put in in WCF terms, it does not have an OperationContract , so when you consume this service, there is no web service operations to call on it ), This application only accepts pure XML as request and returns xml as response.

This is chaos, i know some hackers would say there is no biggy here, just construct an string as xml, send it over to the REST service and get the response as string and use linq or manually tranverse the string and construct an object from it. Wao! this indeeed is a hacky packy solution (Forgive me hackers brothers, i do not intend to cross the line). We are now in the world of objects, things have changed, newer platforms have emerged.

The diagram above speaks more of my scenarios, XML input and XML output using the good old REST Service approach. How am i suppose to translate these XML returned as string into object , how does WCF Channel Factories come into play with these. Keep focus, i will explain how i did the magic ...

First : Call the service from web browser , or get the schema of all the objects returned by the service. I chose the first option for my scenario as there was no schema, so what did i do, i called the web service from a browser , saved it as anything.xml , then i opened visual studio command prompt , ran the XSD.EXE command using the following parameters :

xsd anything.xml /outputdir:mydir



The command above, generates the schema from the xml which i saved from the browser called anything.xml. Now that i have my .xsd file handy, i can generate a .net class using the same xsd.exe command but with different parameters. Thats the price to pay.

Now i have anything.xsd in my output directory , i would like to generate .net classes using the follwoing command :

xsd /c anything.xsd

This generates C# classes for me. Now i am equiped with the object representations of the XML that the REST service sends to my consuming applications.

Second : How do i send request and recieve response from the REST Service ?

To do this, you would need to understand how to use low level WCF communication classes to send soap messages back and fort. First i want to have a mechanism that will enable me to serialize and de-serialize my soap messages Request messages : The following is an example request object :

Sample XML Request

<hellorest>
<message>Get Hello world </message>
</hellorest>

Now that we have carefully reviewed the generated c-sharp class we can proceed to creating the request object. Since we have the request xml above, we will have to hand code this as a c-sharp class. Using the good old System.Xml.Serialization namespace, we would decorate our request class with xml attributes for pure serialization. Here is our sample request object and a Serialization method :


[XmlRoot( "hellorest" )]
public class RESTWebRequest
{
[XmlElement( "Message" )]
public string Message
{
get;
set;
}

public RESTWebRequest( )
{

}

public XmlElement SoapSerialization( )
{
XmlSerializer serializer = new XmlSerializer( typeof( RESTWebRequest ) );
StringWriter writer = new StringWriter( );

serializer.Serialize( writer , this );

XmlDocument xmlDocument = new XmlDocument( );
xmlDocument.Load( new StringReader( writer.ToString( ) ) );

return xmlDocument.DocumentElement;
}
}


Having done that, we are ready to use the communication classes within WCF from the lower level to send our request object and receive our response as object too. To do this, we need to understand the following classes with the System.ServiceModel namespace :

1. Message : Wraps the request/response in a soap envelope.
2. BasicHttpBinding : Communication ensured via HTTP .
3. IRequestChannel
4. IChannelFactory

The listed interfaces and classes would be used to send and recieve , serialize and de-serialize soap messages. Now the long awaited class, the RestAgent which will be used to send and recieve messages is defined below :





internal class RESTAgent : IDisposable
{
IChannelFactory channel;

internal string EndPoint { get; set; }

internal RESTAgent( string EndPoint )
{
BasicHttpBinding basicHttpBinding = new BasicHttpBinding( );
basicHttpBinding.MaxReceivedMessageSize = 1000;
this.EndPoint = EndPoint;

channel = basicHttpBinding.BuildChannelFactory
(
new BindingParameterCollection( )
);

channel.Open( );
}

internal GeneratedFromXSD GetResponset( RESTWebRequest webRequest )
{
Message requestMessage = CreateIncomingMessage( webRequest );
IRequestChannel requestChannel = GetRequestChannel( );

requestChannel.Open( );

//Hey. time out here is ugly.
Message responseMessage = requestChannel.Request( requestMessage , new TimeSpan( 1 , 20 , 00 ) ); //1 hour

requestMessage.Close( );

GeneratedFromXSD anything = DeserializeXMLStream( GetMessageContent( responseMessage ) );

responseMessage.Close( );

return anything;
}

private GeneratedFromXSD DeserializeXMLStream( string xmlStream )
{
XmlSerializer serializer = new XmlSerializer( typeof( GeneratedFromXSD ) );

return ( GeneratedFromXSD ) serializer.Deserialize( new StringReader( xmlStream ) );
}

private string GetMessageContent( Message message )
{
XmlDictionaryReader xmlReader = message.GetReaderAtBodyContents( );

return xmlReader.ReadInnerXml( );
}

private System.ServiceModel.Channels.Message CreateIncomingMessage( RESTWebRequest request )
{
XmlNodeReader reader = new XmlNodeReader( request.SoapSerialization( ) );
return Message.CreateMessage( MessageVersion.Soap11 , "" , reader ); //Give us the real thing. Wrap up with soap envelope without a specific action = ""
}

private IRequestChannel GetRequestChannel()
{
return channel.CreateChannel( new EndpointAddress( EndPoint ) );
}

public void Dispose( )
{
channel.Close( );
}
}


You can use the RESTAgent class to send and recieve soap message from our Restful service by using the follwoing :



RESTWebRequest request = new RESTWebRequest();
request.Message = "Hello world";

RESTAgent agent = new RESTAgent( "http://localhost/restapi" ); //Parameter is the endpoint address

GeneratedFromXSD anything = agent. GetResponset( request );

Monday, September 8, 2008

How to implement a generic WCF message interceptor:

In a changing business environment and business processes; changes affects not only the entire work force, cooperate partners, the way businesses are done and of course our tools that makes our work life better. We are left with the choice of ensuring that our legacy or existing system inter-operate well into our new ways of life and they deliver the expected result that yields expected ROI. Because for today's business to survive, we need to carry along with us our efforts of yesterday, we need to have decoupling in mind when we are integrating services for a wider business sector. These were the thoughts in Microsoft when it first launched the framework (WCF) that shook the whole distributed computing industry.

Windows Communication Foundation is a Microsoft initiative of building Service Oriented Applications that leverages yesterdays and todays technologies, in fact it complements existing distributed technologies. The WCF (Windows Communication Foundation) infrastructure is built into .NET 3.0/3.5 and can be leveraged for different kinds of communication types/endpoint, that ranges from Message Queue, TCP communication, standard webservices, service based webservices. The most commonly used approach is the Service based where you can host it as .asmx or .svc.

In a typical WCF implementation, we have the following :

  • Datacontract. Represents the data that will be wired from one endpoint to the other. Any CLR compliant type marked as datacontract can be serialized and wired over the communication protocol.
  • Message Contract : Think of messages as envelopes, that wraps up our data/data contracts over the wire. Our message have a body and header section. It is analogous to SOAP envelope, in-fact it is converted to a SOAP envelope when the message serialization begins at runtime.
  • Service Contract : Here is the interface that is marked [ServiceContract] which can be called remotely by clients of the service. In our service, we will implement this interface and provide business functionalities that clients will consume and call remotely. Services can expose one - To - Many endpoints (Listener point), and more than one service operations can be exposed by an endpoint.
  • Service Endpoint : Think of an endpoint as message gateways for services that are hosted. A service can be configured to listen for request in different endpoints. A service Endpoint has an Address, a Binding, and a Contract.
  1. An address that describes the location where messages can be sent.
  2. A Binding specifies the type of communication that an endpoint can make using protocols such as HTTP, TCP, MSMQ and security requirements such as SSL, WS-Security etc.
  3. Contract : The binding contract are sets of messages that defines sets of operations that can be accessed by the service clients.

Message Oriented Concept In WCF
I mentioned above that the service contract defines operations that are used to send request and response messages over the transport layer defined by the service endpoint. In a simple client/server architecture, messages can be coupled between sending interface and the receiving end. That is there is a stub and skeleton relationship between the service and the consumers. Although, there is noting wrong in the stub and skeleton approach, that is a client\consumer keeps a stub or proxy of the services that it can talk to. This means when a service changes the client is regenerated using svcutil.exe tool for re-generation of the service stubs.

In an ever changing world of buisiness, we need to build services with simplycity in mind, conformance to changes. How do we allow a generic communication between our service and the rest of the world. Thinking about generic-ability of our services, we need to create an interceptor service that sits in between our clients and services, although the contract binding will be between our client and service, but the address binding will be between our client and the interceptor.

Having understood the basics of the WCF fundamentals, we need to now understand how to pass messages in a generic context.

The Interceptor Pattern
This pattern came into mind when i fell deeply into a WCF scenario that requires changing of service messages or re-delegating a service request to other service other than the requested one. Also you can use this pattern to achieve load-balancing amongst services.

One of the reason's why you might want to use an interceptor pattern is the following :
  • Expose a single entry to the entire world with the interceptor/facade.
  • Do load - balancing with the interceptor.
  • Expose a REST (Representational State Transfer) to the world while your back - end service supports WCF semantics, so you need an interceptor to bridge the gap between the pure xml and soap messages required by the WCF services.
  • Manipulating/ validation on the facade/interceptor end before delegating to the actual service.
  • A form of clean architecture design pattern
  • Securability as single entry is used as the entry point. Security is focused on that single entry instead of all
  • etc
The list above goes on and on without end, and there isnt a limit to what our services mediator can achieve. So how do we do the coding (Good Question) : so lets start with defining our service contract :


[ServiceContract(SessionMode = SessionMode.Allowed)]
public interface IRequestDispatcher
{
[OperationContract(IsOneWay = false, Action = "*", ReplyAction = "*")]
System.ServiceModel.Channels.Message ProcessMessage(System.ServiceModel.Channels.Message message);
}


Note the ProcessMessage operation in our IRequestDispatcher contract, this operation accepts and return a Message from the System.ServiceModel.Channels namespaces and it is the only operation that we need to generically or intercept message calls from client and server.

You will also note that the ProcessMessage method is decorated with [OperationContract(IsOneWay = false, Action = "*", ReplyAction = "*")]. This is to tell our service that our method (ProcessMessage) can process any operation call from different client, by marking it Action = "*" and ReplyAction = "*" . This is the basic of our interceptor strategy.

The Big Picture
Lets have a simple picture of what we want to achieve. We have two WCF services one accepts a string and returns a string, the other accepts an object and returns a string. This services are our back office operations that is open to services that are within our domain. Assuming we want to expose this services to the entire world, we will end up exposing two services. So, if any of the services changes, that means the entire world will have to change with it, this is quite burden some. So, instead of exposing the two services, we have to expose only one service that is generic to all other services, and this service communicates in REST - FUL manner (pure XML and no soap messaging).

Lets define the big picture of



Command architecture and dependency injection

On a recent project, we were mapping commands to user intentions, covering all aspects pertaining to the usage of the application from the p...