Thursday, February 23, 2012

WCF Extension Points, How to extend WCF framework to add custom features in WCF runtime.

 

In one of my SOA based software system, I had a requirement of intercepting the service method calls to automatically logging the method calls on entry and exit of the service method call without putting any logging statements inside the service method implementation and to have some default exception handling logic again without putting any try catch blocks inside service method implementation. The implementation of these features was giving us more cleaner implementation of business functionality inside service methods by abstracting away the implementation of crosscutting concerns like exception handling or logging in my case. 

To implement the above feature I was looking for the way to get execution control even before it goes to my service methods. Good news is that WCF itself helped me and gave the control with the help of it's extension points. Lets see how?

 

Proxy and Dispatcher

 

WCF works on messages which are send between client and service. Every time client wants to call a service  method, it sends a message to service with help of Proxy running in the client process. Job of the Proxy is to take the client request and convert it into a message which is than further serialized and transferred to the service. At service end this message is received by Dispatcher. Dispatcher takes the message and desterilizes the content into appropriate CLR type, finds out which method has to be called on behalf of the client and calls that method.

 

Both Proxy and Dispatcher provides many extension points using different interfaces. When you implement these interfaces in your own class and register those class with WCF runtime (we will see how?), Both Proxy and Dispatcher calls the implementation in your class at the time of message processing. 

 

Lets see what all interfaces are provided via WCF framework to intercept the message processing.

 

  1. IParameterInspector : Called before and after invocation to inspect and modify parameter values.

 

  1. IDispatchMessageFormatter/IClientFormatter : Called to perform serialization and deserialization.

 

  1. IDispatchMessageInspector/IClientMessageInspector : Called before send or after receive to inspect and replace message contents.

 

  1. IDispatchOperationSelector/IClientOperationSelector : Called to select the operation to invoke for the given message.

 

  1. IOperationInvoker : Called to invoke the operation.

 

 

Registering your inspector class with WCF runtime

 

You use WCF behaviors to register your inspector classes with WCF runtime. When the ServiceHost initializes the service, it looks into app.config/web.config file  for the behaviour to apply and also reflects over all the attributes applied on service contract methods to check if any attribute has been applied which is implementing any behaviour interface. If it finds one, it creates an instance of that attribute type and calls appropriate methods of behaviour interface, implemented by attribute class, to you give you a change to register your interceptors during service initialization.  There are following types of behaviors provided via WCF

 

  1. IServiceBehavior: Allows you to register your inspectors at Service level.
  2. IEndpointBehavior: Allows you to register your inspectors at Endpoint level.
  3. IContractBehavior: Allows you to register your inspectors at Service Contract level.
  4. IOperarionBehavior: Allows you to register your inspectors at each Operation level.

 

All these behavior interfaces are having same methods but the method signatures are different so that your only get those runtime objects which comes under the scope you want to extend. Following are the methods available in each behavior interface.

 

  1. Validate: Called just before the runtime is built—allows you to perform custom validation on the service description.

 

  1. AddBindingParameters: Called in the first step of building the runtime, before the underlying channel is constructed—allows you to add parameters to influence the underlying channel stack.

 

  1. ApplyClientBehavior: Allows behavior to inject proxy (client) inspectors. this method is not present on IServiceBehavior.

 

  1. ApplyDispatchBehavior:Allows behavior to inject dispatcher inspectors.

 

 

 

Now you know what all classes and interfaces are available from WCF to extend its runtime, lets extend the runtime to intercept the service method calls and log the entry and exit of method call automatically (without writing logging code in service method implementation).

 

Following are the classes involved in my solution. To make the sample as simple as possible I have create all these classes and interfaces in single WCF project.

 

image

 

Code for LoggingAttribute.

 

Note how this class is inherited from Attribute class and implementing IOperationBehavior. Methods of IOperationBehavior will be called by ServiceHost at the time of service initialization process to give you a chance to register your inspectors. In this example I am registring LoggingInspector instance.

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.ServiceModel.Description;

 

namespace SampleService

{

public class LoggingAttribute : Attribute, IOperationBehavior

{

        public void AddBindingParameters(OperationDescription operationDescription, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)

        {

            //for this example no implementation is required in this method.

        }

 

        public void ApplyClientBehavior(OperationDescription operationDescription, System.ServiceModel.Dispatcher.ClientOperation clientOperation)

        {

            //for this example no implementation is required in this method.

        }

 

        public void ApplyDispatchBehavior(OperationDescription operationDescription, System.ServiceModel.Dispatcher.DispatchOperation dispatchOperation)

        {

            //Register your inspector class

            dispatchOperation.ParameterInspectors.Add(new LoggingInspector());

        }

 

        public void Validate(OperationDescription operationDescription)

        {

            //for this example no implementation is required in this method.

        }

    }

}

 

Code for LoggingInspector.

 

See how LoggingInspector is implementing IParameterInspector interface and providing the logging functionality.

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.ServiceModel.Dispatcher;

 

namespace SampleService

{

    public class LoggingInspector : IParameterInspector

    {

        public void AfterCall(string operationName, object[] outputs, object returnValue, object correlationState)

        {

            //Your can put any logging code here. here is the dummy one.

            Console.WriteLine(string.Format("Method exit : {0}",operationName));

        }

 

        public object BeforeCall(string operationName, object[] inputs)

        {

            //Your can put any logging code here. here is the dummy one.

            Console.WriteLine(string.Format("Method entry : {0}", operationName));

 

            return null;

        }

    }

}

 

 

Code for ISampleService service contract interface.

 

Here I am applying my own custom attribute to enable automatic logging on IncrementNumber method.

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.ServiceModel.Web;

using System.Text;

 

namespace SampleService

{   

    [ServiceContract]

    public interface ISampleService

    {

        [OperationContract]       

        [Logging]

        int IncrementNumber(int number);       

    }   

}

 

 

Code for SampleService implementation.

 

Note that there is no logging related implementation inside IncrementNumber method implementation.

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.ServiceModel.Web;

using System.Text;

 

namespace SampleService

{   

    public class SampleService : ISampleService

    {     

        public int IncrementNumber(int number)

        {

            return number++;

        }     

    }     

}

Why WCF when there are other technologies to implement distributed software systems?

 

Need for distributed software systems.

How do you create distributed application?

 

At architectural level you design your software systems by breaking the business functionality into multiple components and than deploy these components on separate process and machine boundaries.  All these components running on separate process and machine boundaries has to have some communication between them using some protocol so that they can collaborate to achieve the overall business functionality.

 

There have been many technologies available to develop the components and deploy them in distributed manner. Following are some the examples

 

  1. .Net Remoting
  1. COM and DCOM
  2. CORBA  and RMI
  3. Microsoft Enterprise Services

 

So what's wrong in using the above technologies to create distributed apps?

 

There is nothing wrong creating a distributed application using these technologies until your application is going to be used outside the organization or department and not going to interact with other applications in future. When the need to interact with other application comes in, it becomes really hard to achieve the desired interaction among applications because of the mismatch in data structures and protocol stack between your and other applications. Interoperability becomes  an issue because of proprietary standards and protocol stacks used to develop the applications. Other than interoperability issues, all these technologies has a limitation where firewalls can block the communication between components. 

 

How do you tackle with interoperability among distributed components?

 

We use web service technology in which components are exposed to other components using xml based open web standards (SOAP , WSDL, HTTP). These standards are acceptable throughout the software industry. As these standards are based on XML and HTTP which are supported on all platforms, components exposed using these standards are easily accessible between different platforms, ex a components running on windows platform can be accessed via components running on Unix platform. Following are some of the web service elements which makes interoperability possible.

 

Standard protocol: Functionality is exposed via interfaces using one of the few standard Internet protocols such as HTTP, SMTP, FTP, and so on. Mostly used protocol is HTTP.

 

Service description: Web services need to describe their interfaces in detail so that a client knows how to “consume” the functionality provided by the service. This description is usually provided via an XML document called a WSDL document. (WSDL stands for Web Services Description Language.)

 

Finding services: Users need to know what web services exist and where to find them so the clients can bind to them and use the functionality. One way for users to know what services exist is to connect to the listing of services. These listings are implemented via Universal Discovery, Description, and Integration (UDDI) repositories.

 

From above text it should be clear that there are many technologies available to implement distributed components with there own specific advantages and disadvantages and you should web services to expose your components outside your organization or department boundaries because of its open standards support all around in software community.

 

Now imagine that your organization or department needs to develop an application which has to be used internal to your organization and will also be accessed from outside your organization or department.  You might go and use .NET Remoting to expose your serviced components for internal users and will have to used web services to expose same components  to the users outside your organization. But if you do this your code base for the components will have the knowledge for both the technologies being used to expose the functionality as a service. Your developers will be investing more time in dealing with the technology implementation rather than the business functionality implementation.

 

What if you can abstract away the fact from your code base that your component is going to be exposed using multiple protocols and technologies? What if you can enable or disable any protocol in your already running component without stopping it or doing any code changes?  All these features were kind of dream before WCF came in market.

 

WCF introduction

(Develop once and use anywhere)

 

WCF is new Microsoft technology, actually a framework build upon .NET framework, which makes it really easy to develop serviced components and deploy them using multiple communication protocols. It supports net.tcp, net.pipe, HTML, HTTPS and MSMQ communication protocols. Biggest advantage of using WCF is that the knowledge of what all protocols are being used to expose your component is completely abstracted from the component code.  WCF framework is highly extendible as well. It provides so many extension points using them your can implement your own protocols and control almost all the expects of exposing your component as service. 

 

Following are main goals of WCF

 

  1. Unification of existing technologies: WCF subsumes the best of all the distributed technologies. WCF brings together the efficiency of ASMX, the gift of merely adopting transactions with Enterprise Services just through using attributes, the extensibility and flexibility of .NET Remoting, the supremacy of MSMQ for building queued applications, and WSE’s interoperability through WS-*. Microsoft took all these capabilities and built a single, steady infrastructure in the form of WCF.

 

image

 

 

  1. WCF As a Service-Oriented Development Tool: WCF offers that foundation for service-oriented applications by supporting all the four tents of SOA mentioned in my post.

 

image

 

  1. Coexisting with Existing Technology: WCF takes all the capabilities of the existing technology stacks while not relying upon any of them. All your existing investments will run side by side with WCF. Applications built with these earlier technologies will continue to work unchanged on systems with WCF installed. It also provides you with an opportunity to communicate with, or even replace, existing Windows communications APIs and technologies, including ASMX, ASP.NET web services, Web Services Enhancements (WSE), Enterprise

Services, System.Messaging, and .NET Remoting.

Friday, February 3, 2012

Service Oriented Architecture


Problem :
In todays business environment, where customer requirements and demands are changing frequently and businesses are operating in heterogeneous markets, business process automation requirements are becoming more complex and new changes to business processes are coming so frequently. Business are asking for software systems which are highly integrated, easy to modify , highly scalable and customizable so that the changes to business processes and requirements can be accommodated easily with less cost and efforts.
To achieve all these business need, software systems has to be highly modular, business functionality from different business units should be divided into distributed components and these components should be accessible in location transparent way and should be highly interoperable.  System components should be deployed across process and machine to deal with performance bottleneck, to introduce security boundary and to facilitate enterprise level reuse.

Question is how do we do it?

Here, Service Oriented Architecture Comes as rescue. SOA is an architectural style or I would say a reference architecture which guides architects on, how they should decompose business functionality into components and how does the functionality of these components is available to other components. SOA brings the concepts of public contracts, policies and interoperability. Because of these concepts, system components can communicate with each other without worrying about the technology, other component has been implemented.  SOA also posses some constraints on component design and the design of communication links between components.

What is Service?

The term service has different meaning at different level of abstractions. At system architecture level, service is a business functionality which is distributable and is accessible to consume in some way.  It is a window through which business functionality cab be reached. 

Consider the application architecture in Following figure. The client application represents an Agency Management
System that includes many chunks of business functionality such as Certificate Issuance, General Ledger, CRM, and Reporting. The client application coordinates access to these features by consuming business components directly. In
this case, components are not distributable in such a way that they can be location transparent, thus they are not services.

 image


So how do you implement a service in SOA?

You expose your system components as serviced components using different distributed technologies. Some of the technologies you can use are : Enterprise Services, a .NET Remoting component, an ASMX web service , or a WCF service. Any of these technologies can be useful in exposing the business logic in such a way that the client can reach that functionality at remote locations in a distributed environment, without communicating directly with the business
components.

Following is an updated diagram of Agency Management System. Here each business functionality is exposed using one of the distributed technologies. Serviced components are reached using DCOM over TCP,.NET Remoting components via RPC over TCP,ASMX web services via SOAP over HTTP, and WCF services via SOAP over any protocol.

image

The point is that services are not necessarily web services—they are merely chunks of business functionality exposed in some way such that they respect the tenets of SOA.

Some of the constraints SOA poses on serviced components

  1. Service boundaries are explicit : Services are responsible for exposing a specific set of business functionality through a well-defined contract, where the contract describes a set of concrete operations and messages supported by the service. Services completely encapsulate the coordination of calls to business components in response to operations it exposes to clients. Implementation details behind the service are unknown to clients so that any technology platform could be invoked behind the service without impact to the client. In addition, the location of the service isn’t important to the client as long as the client knows where to reach it. All the distributed technologies provide a way to expose your system components by following this constraint.

  1. Services are autonomous : Services encapsulate business functionality, but they must also encapsulate other dependencies of the business tier. In this way the entire service should be moveable or even replaceable without impact to other services or system functionality. A service represents a major chunk of business functionality that owns its own business components, data access components and data storage if applicable. It should be able to perform key functions without external dependencies. This is what is meant by atomicity.

  1. Clients and services share contracts, not code : As service boundaries are explicit, Contracts are used to define this boundary to client application. The contract must not change once published, or must at a minimum remain backward compatible to existing clients.

  1. Compatibility is based upon policy: While contracts describe the business functionality available at a service boundary, policy describes other constraints, such as communication protocols, security requirements, and reliability requirements.


If the above information is useful, Please provide your valuable feedback.

Thanks.

Wednesday, February 1, 2012

Hosting WCF/Workflow Service in IIS directly from Visual Studio 2010 and start debugging by just hitting F5 on Visual Studio.


Problem :
When you develop a WCF/Workflow service using Visual Studio and try to run it, by default Visual Studio runs it under web development server. Here the problem is that the web development server is a light weight host and does not support reach features which comes with IIS. For example web development server does not allow you to run a WCF/Workflow service, which is configured to use NET TCP binding. There are many more such features which does not come with web development server.
As a developer we all want to, just hit the F5 button and start debugging. But if your WCF/Workflow service is configured in such a way that it can only run under IIS, it becomes really tricky to start debugging it.
The common approach we generally follow is to find out in which w3wp.exe our service is running and than attach the Visual Studio to that process.
In following text, I have shown another approach in which Visual Studio can be configured to run together with IIS. With this configuration your WCF/Workflow Services runs under IIS as soon you hit the F5 and you can start debugging without any hassles.
  1. Create WCF/Workflow service. See how to create basic Workflow WCF Service.

  1. Configure IIS to host your WCF/Workflow service. 

(Note :- You can skip following steps if you already a some IIS website configured on port 80 and NET
TCP binding is configured. )

  1. Open IIS Manager.
  2. Add new application pool.
    1. Select 'Application Pools' node from the left hand side tree view.
    1. Click on 'Add Application Pool' link from 'Actions' panel at right hand side.
    2. Give Some name to your application pool. I have given name as 'WorkflowService'. In below steps I will refer your application pool as 'WorkflowService'.
    3. Change .Net Framework Version to 4.0
    4. Click 'Ok'

image

  1. Add new 'Web Site Application' for your services.
    1. Select 'Sites' node from the left hand side tree view.
    2. Right click on 'Sites' node and click 'Add Web Site'
    3. Give Some name to your Web Site. I have given name as 'WorkflowService'. I have given name as 'WorkflowService'. In below steps I will refer your website as 'WorkflowService'.
    4. Change Application Pool name to 'WorkflowService'
    5. Provide some directory path to create IIS virtual directory for this new web site.
    1. Provide host name as 'localhost'
    1. Click 'Ok'
 (Note : While clicking on Ok button you might get a message saying that some other website is already configured to run on port number 80. You just need to close the already running website and start your newly created website.)

image

  1. Configure NET TCP Binding
    1. Right click on 'WorkflowService ' web site and click on 'Edit Bindings' to open 'Site Bindings' dialog.
    1. Click on 'Add' button to open  'Add Site Binding' dialog.
    1. From 'Type' dropdown select 'net.tcp'.
    2. Type 808:* in Binding Information text box.
    3. Click Ok.

clip_image001clip_image002[3]



  1. Enable NET TCP Binding on Web Site.
    1. Select 'WorkflowService' website node from left hand side tree view.
    1. Click on 'Advanced Settings' from 'Actions' panel at right hand side.
    2. Update 'Enabled Protocols' field by adding comma delimited value as 'net.tcp' at the end of the existing value.
    3. Click 'Ok'

image

  1. Configure Visual Studio Project settings to use IIS as service host instead of default web development server.
    1. Select your service project in Solution Explorer and press ALT+ENTER to open project properties dialog.
    2. Click on 'Web' tab on project properties dialog.
    3. On 'Web' tab page, select 'Use local IIS Web Server' radio button.
    1. Click on 'Create Virtual Directory' button to link your website project with IIS.
(Note: This step will fail if Visual Studio is not running in Administrator privileges.)

image

At this stage you have successfully configured IIS and Visual Studio to work together and help you debugging your WCF/Workflow services by just hitting on F5 button on Visual Studio.

If the above information is useful, Please provide your valuable feedback.
Thanks.

Create Workflow WCF Service using Visual Studio 2010.



Create Workflow WCF Service.

  1. Open Visual Studio 2010.
  2. Setup the Workflow WCF Service project using 'WCF Workflow Service Application' template.

image

  1. Rename ‘Service1.xamlx’ to ‘WorkflowService.xamlx’.

  1. Update 'ReceiveRequest' Activity properties.
    1. Open the Property Window for ‘ReceiveRequest’ activity.
    1. Change ‘OperationName field value to ‘PingService’.
    1. Change ‘ServiceContractName’ to ‘WorkflowService.IWorkflowService’.

  1. Update Workflow Variables in 'Variables' pane.
    1. Click on 'Variables' tab just below the Workflow Designer Area to open it.
    2. Change the 'Variable Type' column of 'data' variable to 'String' type.

           image

  1. Add new activity to implement some logic for Workflow Service.
    1. Open ToolBox Window.
    2. Open 'Primitives' Category.
    3. Drag ‘InvokeMethod’ activity between 'ReceiveRequest' and 'SendResponse' Activities on Workflow Designer.

  1. Write some code which will be invoked by workflow.
    1. Add new class to project with name ‘WorkflowServicePingImp’.
    2. Add a static method to the ‘WorkflowServicePingImp’ class with the name ‘PingResponse’. This method will take a string argument and return a string value as response.
    3. Compile the solutions.

image

  1. Update 'InvokeMethod' Activity properties to invoke our implementation from 'WorkflowServicePingImp' class.
    1. Open the Property Window for ‘InvokeMethod’ activity.
    2. Change the 'TargetType' field value to ‘WorkflowServicePingImp’.
    1. Change the 'MethodName' field value to ‘PingResponse’.
    1. Change the 'Parameters' collection by adding new parameter with 'Value' field as 'data' , 'Direction' as 'In' and 'Type' as 'String'.
    1. Change the 'Result' field value to 'data'.

image
Run and Test the Workflow Service Directly from Visual Studio 2010.
  1. Right click on 'WorkflowService.xamlx' file and click on 'Set As Start Page' to set it as start up page for the project.
  1. Press F5 to run the solution.  ( Visual Studio will run the workflow service in development server in some arbitrary port.)
  1. WCF test client will comp up.
image
  1. Double Click on 'PingService' node on left hand side tree view.
image
  1. Put some string in the 'Value' column in 'Request' panel.
image
  1. Click on 'invoke' button.
  2. Output will be shown in 'Response' panel. 

image

If the above information is useful, Please provide your valuable feedback.
Thanks.