Posts Tagged ‘WCF’

Great conference

Wednesday, March 14th, 2007

The Miracle SQL Server Open World conference was a great success. There were lots of informative sessions and great networking. I spoke to a lot of interesting people from all over the world including Microsoft SQL Server guys from Redmond and one as far away as from Brisbane, Australia. Bear in mind that this conference is held in the countryside, far away from anything, two hours drive from Copenhagen, Denmark.

I promised the attendances’ at my session “Transactions with Windows Communication Foundation” to post a guide to setup the Distributed Transaction Coordinator (DTC) for WCF. I have posted two guides:

Hope to see all of these interesting people again at next year’s Miracle SQL Server Open World conference.

Configuring the DTC for WCF with WS-AtomicTransaction

Monday, March 12th, 2007

If interoperability with other platforms is a requirement WS-Atomic Transaction must be used. It requires all the steps for DTC setup in previous blog entry Configuring the DTC for WCF for OleTx, but also a couple of additional ones.

If running Windows XP or Windows Server 2003 a hotfix is required as detailed in the .Net framework 3.0 release notes. The hotfix can be downloaded from here.

WS-Atomic Transaction requires a certificate to establishing Mutual Trust between the parties in a transaction. If a certificate issued by a trusted 3rd party is not available, it is possible to issue one for test purposes by running the below statement in the Visual Studio 2005 Command Prompt. It generates and installs a certificate in the LocalMachine\MY store.

MakeCert -sr LocalMachine -pe -n “CN=mytestcertificate.com” -ss My -sky exchange -sp “Microsoft RSA SChannel Cryptographic Provider” -sy 12

To enable a graphical interface for the WS-AtomicTransaction Configuration Utility (wsatConfig.exe) register the WsatUI.dll by running the following command in the Visual Studio 2005 Command Prompt

regasm /codebase %PROGRAMFILES%\Microsoft SDKs\Windows\v6.0\Bin\WsatUI.dll

Now open the DTC configuration again by the following steps:

  • Administrative Tools | Component Services | Computer | My Computer.
  • Right-click on My Computer and chose Properties – notice a WS-AT tab is now available
    – select it.
  • Check Enable WS-Atomic Transaction network support
  • Select the certificate under Endpoint certificate

WS-AtomicTrnasaction configuration

Now everything is ready to make use of WS-Atomic Transaction in WCF as long as the client and service are on the same machine.

If the client and service are located on different machines, each machine needs a certificate and any machine participating in a transaction must be explicitly authorized by establishing trust with the counterpart’s certificate.

Establishing trust and authorizing trust. These steps have to be performed on all parties.

  • Export the public key
  • Add the public key certificate to the counterpart’s LocalMachine\MY and LocalMachine\ROOT
    stores.
  • Authorize the counterpart’s certificate in the WS-AT tab.

It seems like a daunting task, but it is worth it. I can’t figure out how I ever got by with old-style ASMX web services without transactional support.

Configuring the DTC for WCF with OleTx

Monday, March 12th, 2007

When a transaction propagates from one process to another, the DTC (Distributed Transaction Manager) must be utilized, because to two or more independent parties are involved in the transaction.

Beforehand the WCF service must be prepared:

  • Decorate the service contract (interface) with the attribute TransactionFlow and specify
    if it is mandatory or allowed.
  • Specify on the service type (implementation) OperationBehavior attribute that a TransactionScope
    is required.
  • Enable transaction propagation on the binding via the transactionFlow element in the
    configuration file for both service and client.

If the service and client are ready and an attempt to propagate a transaction is executed the following TransactionManagerCommunicationException is thrown:

System.Transactions.TransactionManagerCommunicationException was unhandled by user code Message=”Network access for Distributed Transaction Manager (MSDTC) has been disabled. Please enable DTC for network access in the security configuration for MSDTC using the Component Services Administrative tool.”

That is because the DTC does not allow inbound of outbound network transactions, by default.

Configure the client DTC to allow outbound network transactions and the service DTC to have inbound network transactions. If both client and service are running on same machine, enable both inbound and outbound network transactions.

To enable inbound or outbound network transaction navigate to

  • Administrative Tools | Component Services | Computer | My Computer.
  • Right-click on My Computer and chose Properties | MSDTC tab | Security Configuration.
  • Check Network DTC Access and under Transaction Communication Manager check Allow Inbound, Allow Outbound or both.

Now transaction propagation via OLE Transactions (OleTx) is possible. These are all the bindings that operate in a homogeneous Windows environment.

SQL Server Open World

Wednesday, February 21st, 2007


I’ll attend the Miracle SQL Server Open World conference from March 8-10, 2007 where I will speak about Windows Communication Foundation (WCF) and .Net Garbage Collection on the business intelligence & .Net development track.

Smart guys like Mark Souza, Lubor Kollar, Poul Randall from Microsoft and Kimberly Tripp will be there – will you?

How does Reliable Messaging work?

Tuesday, January 23rd, 2007

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

Thursday, January 18th, 2007

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

Monday, January 15th, 2007

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