Monthly Archives: January 2007

How does Reliable Messaging work?

First of all – why do we need a technology like reliable messaging? That is due to the inherently unreliable of communication networks. Back in the old days when everyone was using dial-up modems people were aware of the (un)reliability of the connection. But these days with xDSL and fiber optic Internet connections you may seldom be aware of connection failures. But history has a way of repeating itself and now applications are make use of wireless technologies like GPRS, UMTS and WI-FI where you notice the unreliability again.

Reliable massaging ensures that messages send over a wire are delivered exactly once, at least once or at most once; even in the presence of component, system, or network failures. If required the messages can also be delivered in the same order as they were sent.

When implementing connected solutions the normal message pattern are; send a message and get a response or acknowledge of some kind back.

Reliable Messaging - send/response

In a “happy day” scenario the message travels back and forth between the initiator and the acceptor with no problems. Initiator and acceptor are used as both clients and servers can initiate a message sequence.

In my experience most organizations developing web services with the .Net 1.x or 2.0 frameworks and ASMX ignore any reliability issues, hoping never to be faced with reliability
problems. (I have done it myself – shhh don’t tell anybody;-))

The difficulty is how to detect if a message is missing and how to recover.

Reliable Messaging - Lost send

In the event of the initiator’s message never arrives to the acceptor and the acknowledge message will never send back to the initiator. This will causes the initiator to resend the message after a period of time. This requires a message store on the initiator so it can resend any lost messages.

Reliable Messaging - Lost response

In this next scenario the message is received and processed by the acceptor but the acknowledge message gets lost. From the initiators perspective this is exactly the same problem as previous where the initiator’s message got lost.

The initiator therefore resends the message, but if the acceptor processes this message again we might be in serious trouble. The message might say withdraw money from your account – we don’t want that!

Consequently the acceptor stores the received message, so it can track duplicate messages and not reprocess the same message over and over again. But the acceptor still has
to send the acknowledge message to the initiator, so it knows that that the initial message got processed. Therefore the acceptor also has to store processed response messages, so it can resend acknowledge messages.

It is easy to comprehend a technology like reliable messaging when the problem is seen in the right context. If you want to dig deeper into specifications of reliable messaging look at the specification of WS-ReliableMessaging or WS-Reliability – it is not hard to read at all. The two specifications solve the same problem but are implemented differently. WS-ReliableMessaging are implemented in Windows Communication Foundation and WS-Reliability is an OASIS standard.

You can read more about the differences in the article: WS-RM and WS-R: Can SOAP be reliably delivered from confusion?

Building a Windows Communication Foundation client

In the previous blog entry I showed how to build a Windows Communication Foundation Web Service.
Now I’ll show you how to build a client for that web service. I’ll build the client in two different ways to show you the possibilities.
If you control both the client and the web service; you can just share the service contract implemented as a regular .Net interfaces – you remember the IHelloWorldService interface… right?

[ServiceContract]
public interface IHelloWorldService
{
  [OperationContract]
  string HelloWorld();
}

On the client you need to create a factory that builds the web service proxy for you, so you can utilize the operation. You do that with the ChannelFactory<> from the System.ServiceModel.dll.

ChannelFactory<ihelloworldservice> factory = 
  new ChannelFactory</ihelloworldservice><ihelloworldservice>(“myEndPoint”);

IHelloWorldService proxy = factory.CreateChannel(); 

MessageBox.Show(proxy.HelloWorld());

Notice the parameter of the ChannelFactory constructor which is the name of the endpoint configuration. The client endpoint configuration is very similar to the web service configuration and is made of ABC (Address, Binding and Contract).

< ?xml version=“1.0“ encoding=“utf-8“ ?>
<configuration>
  <system .serviceModel>
    <client>
      <endpoint name=“myEndPoint“
                address=“http://localhost:8080/HelloWorldService”
                binding=“basicHttpBinding”
                contract=“IHelloWorldService“ /> 
    </client>
  </system>
</configuration>

If you compare this client configuration file with the one for the web service, you will see that they are almost identical.
That is all it takes to implement a WCF client to the HelloWorldService.
You are now thinking – what if you do not have control over the web service or the web service is implemented in another programming language like Java? Then you do not have a service contract implemented as a .Net interface. That is where WSDL comes into the picture.
The web service metadata is not published by default, so you need to do a little server configuration. Don’t worry – it is simple. You just have to change the behavior of the service by defining a behavior and map the service to that behavior.

< ?xml version=“1.0“ encoding=“utf-8“ ?>
<configuration>
  <system .serviceModel>
    <behaviors>
      <servicebehaviors>
        <behavior name=“myBehavior“>
          <servicemetadata httpGetEnabled=“true“
                           httpGetUrl=“http://localhost:8080/HelloWorldService“ /> 
        </behavior>
      </servicebehaviors>
    </behaviors>
      <services>
        <service name=“HelloWorldService“
                 behaviorConfiguration=“myBehavior“> 
          <endpoint address=“http://localhost:8080/HelloWorldService“
                    binding=“basicHttpBinding”
                    contract=“IHelloWorldService“ /> 
      </service>
    </services>
  </system>
</configuration>

The service behavior instructs the service to publish metadata via HTTP by a certain address. Now everybody can retrieve the WDSL file and implement you web service. That can be done with the ServiceModel Metadata Utility (svcutil.exe). This tool automatically implements a .Net proxy class for the web service.

svcutil http://localhost:8080/HelloWorldService /NoConfig

Run the above statement in a command prompt (you need to have the service running) and the tool generates a .Net file called HelloWorldService.cs. This file contains a proxy implementation of the web service enabling you to call the web service without doing any IO programming.
Why did I add the /NoConfig flag – that because the svcutil.exe generates a very verbose client configuration file. The auto generated client configuration file works, but essentially it is the same client configuration file used with the dynamic client.
Add the HelloWorldService.cs file to your solution, add a reference to the System.ServiceModel.dll
and copy the client configuration file from dynamic client (the above client configuration).
Notice you do not need to reference the assembly with the service contract IHelloWorldService.

IHelloWorldService proxy = new HelloWorldServiceClient(“myEndPoint”);

MessageBox.Show(proxy.HelloWorld());

You are done! Build, compile, test, package and then ship you code.
If you want to super simple Visual Studio way of implementing web services – Add Web Reference kind of functionality, you can install Visual Studio Extensions for .Net 3.0 Framework. Then you get an Add Service Reference (similar to Add Web Reference), but all it does is call the svcutil.exe. The extension also includes a GUI configuration editor, which makes you life a lot easier if you are not a XML fetishist.
You can download the working WCF example including the Web Service and the two client implementations here: Hello World WCF with clients

A simple Windows Communication Foundation Web Service

In the old days – pre .Net 3.0, a Web Service required the IIS, a class marked with the WebService attribute and one or more methods exposed by the WebMethod attribute. Something like this:

[WebService]
public class HelloWorldService
{
  [WebMethod]
  public string HelloWorld()
  {
    return “Hello World”; 
  }
}

Optionally you could inherit the service class from System.Web.Services.WebService, if you need access to the HttpContext.

You can still use the “old” way of programming your Web Services, but with .Net 3.0 you have access to a new programming model to expose your services – Windows Communication Foundation (WCF).

With WCF you have to do a little more work, but you get a lot of added functionality out of the box and you do not have to play around with Web Service Enhancements (WSE) – which in my opinion is a plus.

WCF emphasises contract first design. It is easy with WCF, because you do not have to make the WSDL file yourself. You just have to make a regular .Net interface decorated with some attributes.

[ServiceContract]
public interface IHelloWorldService
{
  [OperationContract]
  string HelloWorld();
}

The ServiceContract and OperationContract are part of the System.ServiceModel.dll which is part of the .Net 3.0 framework – so you need to add a reference to System.ServiceModel.dll.

If you look at the pre .Net 3.0 Web Service implementation, you see that it is very similar. The ServiceContract attribute defines the interface and the OperationContract attribute describe which operations you can perform on the service, just like the WebService and WebMethod attributes.

Now you have the contract of your server, by which you actually can produce a WSDL file with the ServiceModel Metadata Utility (svcutil.exe) without doing any handcrafted XML, if you like.

Next you have to implement the interface. The implemented class is called service type.

public class HelloWorldService : IHelloWorldService
{
  public string HelloWorld()
  {
    return “Hello World”; 
  }
}

All that is left is a process to host the WCF Web Service. We could use IIS, but I’ll use one of the new possibilities – a console application. Just because we can!

class Program
{
  static void Main(string[] args) 
  {
    using (ServiceHost host = 
      new ServiceHost(typeof(HelloWorldService)))
    {
      host.Open();

      Console.WriteLine(“The
      HelloWorldService is running.”);

      Console.WriteLine(“Press
      [ENTER] to terminate…”); 

      Console.ReadLine();
    }
  }
}

Before running the application we need to configure a service endpoint – the address, binding and contract. You properly heard about ABC.
The address is the URL, the binding specifies the protocol and data format and we have already made the contract.

Add a configuration file (App.config) and enter the ABC.

< ?xml version=“1.0“ encoding=“utf-8“ ?>
  <configuration>
    <system .serviceModel>
      <services>
        <service name=“HelloWorldService“>
          <endpoint address=“http://localhost:8080/HelloWorldService“
	                 binding=“basicHttpBinding”
	                 contract=“IHelloWorldService“ /> 
      </service>
    </services>
  </system>
</configuration>

The basicHttpBinding is a regular XML Web Service with text encoded SOAP messages transported via HTTP – just like the pre .Net 3.0 implementation.

That’s it. A WCF Web Service.

The beauty with WCF is if you for example want added security, you can encrypt the SOAP body, by using WS-Security, simply by changing the binding in the configuration file to wsHttpBinding. If you ever tried that with WSE 3.0, you know it is a pain.

You can download the working WCF example here: Hello World WCF Service

When is DivideByZeroException thrown?

What a strange question most developers will say. DivideByZeroException
is thrown every time you divide by zero, right? No – it depends.

Let’s try – regular division with integers.

int i1 = 4;
int i2 = 0;

try
{
Console.WriteLine(i1 / i2);

}
catch (System.DivideByZeroException)
{
Console.WriteLine("DivideByZeroException");
}

Hmm, I see a DivideByZeroException coming, and that’s
absolutely correct. So what is all the fuzz about?

Let’s try again, but this time with floating point numbers.

double d1 = 4.0;
double d2 = 0.0;

try
{
Console.WriteLine(d1 / d2);

}
catch (System.DivideByZeroException)
{
Console.WriteLine("DivideByZeroException");
}

If you try to run this piece of code, no exception is
thrown. Instead INF (short for infinite) is returned. To be more precise a PositiveInfinity,
due to the decimalNumerator is positive.

I read this somewhere and had to test it. I even asked
my colleagues when DivideByZeroException is thrown and showed them these code examples.
None of them knew the right answer. So it’s not only me, whom is ignorant. 🙂