Talking Without Speaking, Hearing Without Listening.

In this blog I publish information and ideally have people that subscribe to it. For the blog I use the WordPress hosting site (service) you may use an RSS aggregator to subscribe (client). In a business application you can achieve this same concept easily with WCF. In this post I will run through an example of the Medical System Client application subscribing to patients of interest. When other clients update those same patients with business critical data the active clients can receive an ‘alert’ immediately at easily.

We begin with the client side setup. First we define the contract interface that contains our operational methods (excluded below, but examples include Save(), Retrieve(), etc). The key things to note on the interface is the ‘CallbackContract’ attribute, and the subscribe/unsubscribe methods. The subscription methods use a Patient Id key but this can be whatever is most suitable in your situation, for example an enum will work fine for more generalised event types.

[ServiceContract(CallbackContract = typeof(IPatientEvents))]
public interface IMyContract
{
   [OperationContract]
   void Subscribe(int patientId);
   [OperationContract]
   void UnSubscribe(int patientId);
}

The next step is to define an events interface. This interface outlines expected methods the client must implement to be able to handle the events raised by the service. Note that the event handler has an attribute defining it as a OneWay call. This event is lab results for a patient have been entered into the system, and are of a critical nature.

public interface IPatientEvents
{
   [OperationContract(IsOneWay = true)]
   void LabResultsUpdated(int id, string text);
}

Then you simply create your client side class against the events interface. In this example the client is a WPF page class.

class PatientDetails : Page, IPatientEvents
{
     MyContractClient proxy;
	 
	 //other methods
}

The client will need to supply a context to the service so it can maintain an association on the channel. This is simply achieved through a constructor call when initialising the proxy. Also at this point we’re subscribing to the events for the given ID. This subscription can be client triggered this way. Alternatively certain actions can have the server subscribe the client server side. An example would be during a data retrieval call for a patient; the server forcing the setup up the subscription.

  InstanceContext context = new InstanceContext(this);
  
  proxy = new MyContractClient(context);

  proxy.Subscribe(id);

Now on the service we implement the same contract IMyContract we also define the signature of the delegate Action that will be raised as an event. Along with implementing the method that will attach the event handler to the appropriate client. The key thing to note here is the Current.GetCallbackChannel this is linking via the context the client supplied in the proxy initialisation.

[ServiceBehavior(InstanceContextMode
      = InstanceContextMode.PerCall)]
class PatientService : IMyContract
{
    static Action<int, string> m_EventLabs = delegate { };

    public void Subscribe(int patientId)
    {
        IPatientEvents subscriber = 
          OperationContext.Current.GetCallbackChannel<IPatientEvents>();

        m_EventLabs += subscriber.LabResultsUpdated;
    }
}

All that’s left now is to write the actual event firing code, that can be triggered after an appropriate event. In this example the firing takes place after the Patients Lab Results have been updated. Thereby allowing any other users currently viewing this patient’s details to be alerted.

public static void FireEvent(LabResult labResult)
{
    m_EventLabs(labResult.PatientId, labResult.ToString());
}

public bool SaveLabResults(LabResult lr)
{
    //save code...

    PatientService.FireEvent(labResult);
}

Back on the client we have defined a method that will be executed upon the event. Remember the service has attached the handler on the Subscribe() method.

public void LabResultsUpdated(int id, string text)
{
    this.displayAlerts.Text = text;
}

That is all that is required to have your client quickly and easily subscribe to and handle events. It’s thread-safe and efficient with the service doing all the hard work.

I will expand on [ServiceContract(CallbackContract … ] and [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)] in future posts, and I’ll try to remember to update this post with direct links.

Just for some reference sake here are the objects used above that were not defined in the code blocks:

[DataContract]
public class Patient
{    [DataMember]
    public int PatientId { get; set; }
    //more members
}
[DataContract]
public class LabResult
{    [DataMember]
    public int LabResultId { get; set; }
    //more members
}
//displayAlerts is just a page <TextBlock> object

This MessageHeader will self destruct in 5 seconds

Let’s get our hands dirty with an example you can follow along with. With the basic concepts covered we can whip up something to send some data back and forth. We will start with a simple winform to run our service. Another winform (acting as the client application) to connect to it so our service can do some intended job.

In this post I’m also going to introduce a refined and well developed library of enhancements for WCF. It is created by the very talented Juval Lowy you can find his work at IDesign.net. This library is called ServiceModelEx it is available as a free download, and it is very, very useful. I hope to demonstrate its usefulness in this and future posts. ServiceModelEx is designed to help simplify some of the more complex aspects of WCF along with adding extension to existing features. It makes some aspects of WCF more robust, such as adding TypeSafe alternatives and often adding an overlooked sub-feature (e.g. NetNamedPipeContextBinding I’ll discuss this in a future post).

Once you have ServiceModelEx downloaded and included in your Visual Studio project all you need to do is add a reference to it:

//WCF Service Model:
using System.ServiceModel;
//iDesign Service Model Extensions:
using ServiceModelEx;

In this post I’m introducing a theme for the demos; they will follow the ideas of a medical system. With concepts such as Patient, TreatmentSchedule, MedicalProcedure, Doctor, and other types of system Users (Nurses, LabTechnicians, etc).

On with it.
We are setting up a simple call to a service to create/update/delete a new patient.

To begin we will need to setup some data constructs (they are simplified to keep the code sections short, i.e. no extensive code to setup private members and public properties). A class MsgHeader will act as a common object sent ‘out-of-band’ on all calls to the service. The ‘out-of-band’ concept is used for the purpose of keeping data contracts free of plumbing-related operations. This example uses the header to supply something specific about the user, and the type of operation we are performing (enum OperationTypes). Another example of advanced control data you can pass via headers is a ‘message priority’ value.

[DataContract]
public class MsgHeader
{
    [DataMember]
    public int userRoleId;
    [DataMember]
    public int operationType;
}

A snippet of the data contract, and other setup data:

[DataContract]
public class Patient
{
   [DataMember]
   public int PatientId;
   //more members...
}

public enum OperationTypes { 
   Update = 0, Insert = 1, Delete = 2 }
public enum UserRoles { 
   Reception = 1, Nurse = 2, Doctor = 3 }

The Service is set up with a simple save/retrieve interface:

[ServiceContract]
interface IPatientContract
{
   [OperationContract]
   void SavePatient(Patient p);
   [OperationContract]
   Patient RetrievePatient(int patientId);
}

Via the Client proxy constructor we pass in our populated MsgHeader object. Then call any required methods on the proxy, in this case the save.

//class instance of patient details
public Patient CurrentPatient;

public void Save()
{
   MsgHeader header = new MsgHeader();
   //Set the properties accordingly ...

   //Setup and Call Proxy
   MedicalSystem proxy = new MedicalSystem(header);

   proxy.SavePatient(this.CurrentPatient);

   proxy.Close();
}

Finally on the service implementation to access the MsgHeader you simply use HeaderContext.Current.

class MedicalSystem : IPatientContract
{
   public void SavePatient(Patient p)
   {
      switch (HeaderContext.Current.dataOperation)
      {
         case (int)DataOperations.Delete:
            DeletePatient(p.id);
            break;
         case (int)DataOperations.Insert:
            CreateNewPatient(p);
            break;
         // ...
      }
   }
   // ...
}

There we have it – ‘out-of-band’ passing of data to your service to keep system entities free of the clutter of control data.

Putting all the basics together

Before we get stuck into a full scale example, I’ve prepared a simple checklist of tasks required to get a basic service up and running.

Refer to this checklist to get your first WCF solutions up and running quickly.

Service & (Host)

  1. Service Contract IMyServiceContract
  2. Implementation of that Contract
  3. Service Proxy Implementing ServiceContract & ClientBase<IMyServiceContract>
  4. Endpoints via App.Config
  5. Form/Console to kick off Host

Client

  1. Proxy implementing IMyServiceContract
  2. Endpoints to match those specified in service via App.config

If you haven’t done things right one of the very early exceptions you might receive is an InvalidOperationException and it will name the Contract that you haven’t implemented correctly. This is likely to be caused by a flaw in your app.config (server side).

A Common Exception from a Simple Misconfiguration
A Common Exception from a Simple Misconfiguration

Other exceptions to look out for are those when you attempt to call the service and either endpoints are misconfigured or implementations aren’t complete.

Being a Good Host

Hosting a WCF application is quite simple. There are 3 available hosting options IIS (Internet Information Services), WAS (Windows Activation Service) under Vista/Server 2008 and an ordinary (windows form/console) application.

The quickest to getting your project up and running is a windows form (or console) app. This way you can begin development quickly.

//program.cs
static class Program
{
   [STAThread]
   static void Main()
   {
      Application.Run(new FormWcfHost());
   }
}

Then for the windows form:

public partial class FormWcfHost : Form
{
   private ServiceHost<MyService> serviceManager 
      = new ServiceHost<MyService>();

   public FormWcfHost()
   {
      serviceManager.Open();
   }
		
   private void FormWcfHost_FormClosed(object sender, 
       FormClosedEventArgs e)
   {
      serviceManager.Close();
   }
}

It’s that simple.

The production level hosting decissions are just slightly more involved. Basically if you have an installation of Windows 2008 Server available then it’s ideal to make use of WAS to host it. Otherwise the choice can be argued between IIS6 hosting or just running it as a standard windows service on a Windows 2003 depolyment.

The advantages that WAS offers are; application pooling, isolation, identity management. So is the more scalable choice.

The WCF Run-Down

Windows Communication Foundation (WCF) is a framework for building service-oriented applications. Using WCF, you can send data as asynchronous messages from one service endpoint to another.

Great… Lets try it out…

So how do you go about getting something up and running? We have to start somewhere… so let’s start by covering some of the basic concepts.

Service Contract
The bulk of the work in setting up WCF is achieved by the most simplest of attribute placement on an interface (or class). Best practice is to apply it to an interface.

[ServiceContract]
public interface IMyServiceContract
{
    [OperationContract]
    string GetData(int value);
}

Bindings

Define the configuration of the way messages will be communicated, transported and encoded. The examples being Synchronous vs Asynchronous, HTTP vs TCP, compression vs interoperability. This list and set of comparisons is by no means exhaustive. But for the majority of cases of you’re likely to choose either NetTCP or MSMQ (queued) if both systems (client+server) are using WCF. Otherwise you have an ASMX based client and your choice really should be WSHttpBinding (otherwise you’re supporting a legacy system and you have no choice but to use BasicHttpBinding.

Endpoints

The address to which clients can connect to the service. The key things to note are the protocol type in this case net.tcp, the port (anything high up will do), the bindingConfiguration that allows you to further define the communication method, and the reference to the contract defined earlier. The service can and expose multiple endpoints, and they can each be of varying type and configuration.

<system.serviceModel>
  <services>
    <service name="MyService">
      <endpoint
        address="net.tcp://localhost:8001/MyService" 
        binding="netTcpBinding"
        bindingConfiguration="myNetTcpBinding"
        contract = "IMyServiceContract" />
    </service>
    <bindings>
      <netTcpBinding>
        <binding name="myNetTcpBinding" 
          transactionFlow="true" />
        </netTcpBinding>
    </bindings>
  </services>
</system.serviceModel>

Just a tip if you find yourself debugging calls from a client application and if you’re anything like me and like to edit code live while continuing to debug you will cop a lot of timeout exceptions. It’s therefore handy to setup extra bindings you can use them in development naming them something obviously not required for production like ‘DevExtendedTimeouts’ (hopefully so someone remembers to remove them before shipping) the length of the name itself makes them stand out. This way you have a few more minutes before you get hit with a timeout – alter length to your own taste. In a future post I will cover how this can also be achieved programmatically including the use of compiler directives.

<bindings>
   <netTcpBinding>
      <binding name="myNetTcpBinding_DevExtendedTimeouts" 
         transactionFlow="true"
         sendTimeout="00:05:00" />
   </netTcpBinding>
</bindings>

Client Application

Once the service contract has been imported a proxy responsible for managing the life-cycle and connection to the service is what the client application can invoke to make calls. The client end configuration needs to list all the endpoints exposed by the service that it intends to use. A key thing to note is the client calls via the proxy should always perform a close action, to free up resources on the service. This can simply be achieved via a using() statement, your service implementation should also implement IDisposable.

    using ( IMyServiceContract proxy = new MyClient() )
    {
        proxy.SomeMethod();
    }

Client configuration leads onto the topic of hosting the WCF service which will be the next post “Being a Good Host“.

Pex – Assisted White Box Testing

On a brief side note after attending Mitch Denny’s (from Readify) presentation tonight on “Tools for Improving Software Quality” he introduced us to a great little tool for Visual Studio 2008 and beyond. “Pex (Program EXploration) produces a traditional unit test suite with high code coverage“.

It’s a tool that writes the unit test for you!

This may seem like a contradiction to the purpose of the unit test, and slap in the face for those promoting Test Driven Development (TDD). But that’s incorrect. The purpose of Pex is to assist in catching the missed branches (especially the mundane and tedious ones from switch statements). To be used to polish the unit tests, after the best practice approach is followed; of writing the core of the unit test before coding the actual function begins.

Given a parameterized unit test written in a .NET language, Pex automatically produces a small unit test suite with high code and assertion coverage. To do so, Pex performs a systematic white box program analysis.

Download it here at the Research.Microsoft.com site; available for “Commercial Evaluation” and “Academic Use” as it’s still in Beta.

The tool integrates directly into Visual Studio and assist with MSTest tests. You write click on a method and it explores the code paths determines input variables to test areas of the code your logic currently doesn’t cater for, thereby allowing you to further expand the function itself to cater for more “expected exceptions”.runpex

Here are some more screen shots on the official Pex site, also check out the Channel 9 video on it.

Why WCF

UPDATE 9-July-2010:
This entry gets a lot of random hits, so I thought I would update the information as of July 2010, just to give links to newer areas relating to WCF.

WCF – Windows Communication Foundation, has become in fact more of a foundation for a larger set of abstractions on top it. Simply put WCF is a set of fundamental plumbing components with powerful extensibility features. But is not the easiest of things to use and configure.

The options now for more out of the box ready solutions that wrap and exist on top of WCF are:

These frameworks/abstractions/concepts are intended to simplify creating and deploying your web accessible service offerings.

Original post as it was 24-Feb-2009…

To quote the MSDN front page for WCF:

“It unifies the capabilities in ASMX, WSE, Remoting, COM+, and MSMQ; therefore developers need to learn only one programming model.”

Simply put “it’s where we are with Microsoft.NET framework”, if you’re going to build .NET applications it’s the right choice. Service Oriented Architecture is currently the most practical approach to build robust, distributed and maintainable applications. WCF allows you to simply and easily build such services according to an industry standard, with the intention to achieve a high level of interoperability. WCF takes care of: service interactions, marshalling, type conversions and other protocols allowing the developer to focus less on plumbing and more on delivering application value.

Key WCF notes:

  • Most messages are SOAP messages.
  • Not only for HTTP (can have: TCP, NamedPipes).
  • Can therefore communicate:
    • same machine
      • same app domain
      • cross process
    • cross machine
      • intranet
      • internet
  • Interoperable with other non-WCF services.

What I will attempt to demonstrate in subsequent posts is how simple it is to get the application plumbing working right and smoothly. Also down the track demonstrate some of the more complex scenarios you can setup with WCF especially the capabilities to further extend the framework.

Next up is “The WCF Run-Down“.

WCF Beginners Series

I’ve been issued a task to run a series of presentations for the Microsoft arm of the software development service line of my consulting firm. Focusing on Windows Communication Foundation (WCF) for the .NET framework.

dotnetframework3

This blog will assist in breaking down some of the topics into simple easily referenceable chunks, including links to other relevant articles/blogs/samples online. They will begin of with the very basics ([Service|Data]Contracts/Bindings/Endpoints/Configuration/Hosting), acting as a tutorial to get started then expanding into more advanced topics (Transactions/Security/etc). So stay tuned for those.

The plan once the initial WCF series of posts is complete, to expand further in to other .NET 3.5 streams including WPF and WF. The goal is to deliver real world examples and not purely conceptual discussions. Possibly further depending on how productive I can be.

Look out for the next post “Why WCF“.