Posts Tagged ‘WCF’

How to view default values for a WCF binding

Thursday, April 23rd, 2009

… or create a custom binding from a build-in binding.
… or create an administrative XML-based configuration from an administrative programmatic configuration.

Below codes does all that:

// Specify the source binding
// - Programmatic binding
// - Administrative XML-based binding
// - Convert to custom binding

/* Programmatic binding */
var binding = new BasicHttpBinding();
binding.TransferMode = TransferMode.Streamed;
binding.MaxReceivedMessageSize = 10000;

/* Administrative XML-based binding */
// var binding = new BasicHttpBinding("basicHttp");

/* Convert to custom binding */
// var wsBinding = new WSHttpBinding("wsHttp");
// var binding = new CustomBinding(wsBinding);

string outputConfigFile = "out.config";

Configuration machineConfig = ConfigurationManager.OpenMachineConfiguration();

var fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = outputConfigFile;
fileMap.MachineConfigFilename = machineConfig.FilePath;

Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
config.NamespaceDeclared = true;

var scg = new ServiceContractGenerator(config);

string sectionName, configName;
scg.GenerateBinding(binding, out sectionName, out configName);
config.Save();

The programmatic source binding will create a configuration file with all default values for the BasicHttpBinding except for TransferMode and MaxReceivedMessageSize attributes like so:

<basichttpbinding>
    <binding name="BasicHttpBinding"
             closeTimeout="00:01:00"
             openTimeout="00:01:00"
             receiveTimeout="00:10:00"
             sendTimeout="00:01:00"
             allowCookies="false"
             bypassProxyOnLocal="false"
             hostNameComparisonMode="StrongWildcard"
             maxBufferSize="65536"
             maxBufferPoolSize="524288"
             maxReceivedMessageSize="10000"
             messageEncoding="Text"
             textEncoding="utf-8"
             transferMode="Streamed"
             useDefaultWebProxy="true">
        <readerquotas maxDepth="32"
                      maxStringContentLength="8192"
                      maxArrayLength="16384"
                      maxBytesPerRead="4096"
                      maxNameTableCharCount="16384" />
        <security mode="None">
            <transport clientCredentialType="None"
                       proxyCredentialType="None"
                       realm="" />
            <message clientCredentialType="UserName"
                     algorithmSuite="Default" />
        </security>
    </binding>
</basichttpbinding>

I found this tip by Brian McNamara on the MSDN WCF forum.

Handcrafting the WCF client

Thursday, March 5th, 2009

Two years ago I wrote an article Building a Windows Communication Foundation client, describing three ways of creating WCF clients. I did not mention the fourth one, as I did not know at the time. Now I am older and wiser ;-)

The four ways of creating a WCF client are:

  1. Visual Studio’s “Add Service” reference
  2. Service Model Metadata Utility Tool (SvcUtil.exe) command line tool
  3. Dynamic proxy with ChannelFactory
  4. Handcrafting the WCF client

The last two options are only viable for WCF to WCF implementations where you either have control of both service and client or the service provider supplies a .Net assembly. Because both of them require the service contract aka the .Net interface marked with ServiceContractAttribute and OperationContractAttribute.

Anybody that has tried the “Add Service” reference in Visual Studio knows it is broken. First of all it generates an enormous amount of files, even for the simplest service contract.

Secondly it sometimes corrupts the state of the generated files, so you have to remove the reference and then add it again.. Just try to google it and you will find many frustrated developers. Do not use it!

The SvcUtil.exe is better and has a vast number of options. This is the preferred option for non .Net services or where the service contract interface is not available.

The dynamic proxy with ChannelFactory is useful, but be aware that the interface returned does not implement IDisposable, but the implementation does. See below:

var factory = new ChannelFactory<ihelloworldservice>("myEndPoint");

IHelloWorldService proxy = factory.CreateChannel();

using (proxy as IDisposable)
{
   MessageBox.Show(proxy.HelloWorld());
}

Finally the handcrafted version – the one I want to talk about. Writing the WCF client by hand is fairly easy – it requires the implementation to inherit from ClienBase and implementing the service contract interface. Below is first a simple service contract IHelloWorldService:

[ServiceContract(Namespace = "www.lybecker.com/blog/HelloWorldService")]
public interface IHelloWorldService
{
   [OperationContract]
   string HelloWorld();
}

Next the handcrafted WCF client with constructors and service contract interface implementation:

public class HelloWorldClient : ClientBase<ihelloworldservice>, IHelloWorldService
{
   public HelloWorldClient()
   { }

   public HelloWorldClient(string configurationName) : base(configurationName)
   { }

   public HelloWorldClient(Binding binding, EndpointAddress address) : base(binding, address)
   { }

   public string HelloWorld()
   {
      return Channel.HelloWorld();
   }
}

That’s it. :-)

Now you have full control of the WCF client implementation.

Download the sample application Hello World WCF clients including a handcrafted version

Serialization in .Net 3.5 SP1

Saturday, November 22nd, 2008

In .Net 3.5 SP1 it is now possible to serialize any object that has a default constructor without decorating it with [DataContract] or [Serializable].

Developers have these choices now when serializing objects:

  • Implicit serialization – requires public default constructor and only serialize public read/write fields
  • Use the [Serializable] attribute
  • Use [DataContract] and [DataMember] attributes
  • Implement the ISerializable interface

I must say, that I’m not keen on this new feature. I prefer explicit serialization to implicit serialization. I predict that implicit serialization of entire object graphs will cause performance problems for many .Net developers in the years to come. This could also be a good thing as I am a consultant  ;-)

Aaron Skonnard has a more detailed blog post about the new serialization features in .Net 3.5 SP1.

.Net debugger visualizers

Sunday, October 12th, 2008

The .Net framework 2.0 gave some great tools for debugging – they are a great help when writing code.

Some of these features are the DebuggerDisplay and DebuggerStepThrough attributes. I seldom use any of them, as I prefer to just overriding the ToString method instead of using the DebuggerDisplay attribute. This makes it easy to instrument the code too, as I can reuse the ToString method implementation for tracing.

Another feature is the ability to develop custom debugger visualizers. They enable smart developers to build their own. I find some really useful, especially the WCF visualizer. But there a many – check out this list of custom .Net debugger visualizers.

These small enhancements make it so easy to get an overview of the current state, instead of inspecting properties.

WCF certified

Sunday, April 20th, 2008

I just got word from Microsoft, that I passed the Microsoft Certified Technology Specialist: .NET Framework 3.5, Windows Communication Foundation Applications certification (70-503).

It was not easy, as the preparation guide was incomplete and I didn’t have time to properly prepare for the test. I took the beta exam in January, but had totally forgotten about it.

I am proud to be one of the first to pass this exam :-)

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?