Wednesday, May 25, 2011

WCF Known Types and a Generic Resolver

When using abstract types and in Operation Contracts you must use the KnownTypes attribute (or equivalent web.config syntax) to declare to WCF which what subclasses of the given abstract type are allowed to be used. This works ok, but forces you to declare up front what types can be used and if someone adds a new type they must add a KnownTypes attribute for it otherwise WCF will throw exceptions when it is used over a service call.  This method is a little awkward, and it also violates the Open Closed principal.

Juval Lowry discusses a better more maintainable approach:
Known Types and The Generic Resolver MSDN Magazine February 2011

Tuesday, May 24, 2011

WCF Service Diagnostics Part 1

Sometimes its useful to be able to examine the raw soap messages coming into and out of a service.  Especially when trying to interface into a third party service or client. Quite often all you get is WSDL and not much else.

Back in the days of ASMX Web Services you had to write your own SoapExtension to be able get access to the SOAP/XML. Including all the tedious IO mechanics of writing the log information to an external source. WCF has a built in logging mechanism that just needs to be turned on.  In addition WCF also has its own log viewer.

Enabling WCF Logging
This requires a few modifications to your web.config.  Alternatively you can use the WCF Service Configuration Editor tool from Visual Studio's Tools menu (or located on your disk at: <Program Files (x86)>\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0 Tools)

<?xml version="1.0"?>
                        <filter type="" />
                    <add name="ServiceModelMessageLoggingListener">
                        <filter type="" />
                type="System.Diagnostics.XmlWriterTraceListener, System, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089"
                <filter type="" />
        <trace autoflush="true" />
        <compilation debug="true" targetFramework="4.0" />
                logMessagesAtTransportLevel="false" />


Microsoft Service Trace Viewer
To view a log file double-clicking the file will open it if you leave the extension as *.svclog, The viewer is installed as part of Visual Studio 2010 and will be located on your disk <Program Files (x86)>\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0 Tools).

The complete soap message envelope is shown inside the application data element.  On the left pane use the messages tab to show only messages and look for the items that have a named action. This is the action name used in the OperationContract attributes. Or if left blank it will be as shown above using the TempUri namespace.

Recommended Settings for Production and Development Debugging etc are recommended by Microsoft here:

WCF Test Client
Located at <Program Files (x86)>\Microsoft Visual Studio 10.0\Common7\IDE) and is installed as part of Visual Studio. This is a great simple utility for quickly testing services of any kind.  In fact it will auto start when using the Visual Studio WCF Application project template.

Its great for quick testing of services and viewing request and response xml.

Packet Sniffing
This is useful for sniffing packets at a lower level particularly when you are writing a client that is interfacing into a third party non-Http service.

For Http services it will probably be easier using Fiddler.


Saturday, May 7, 2011

Memory Leak Diagnostics

More often than not the occurance of memory leaks seem to be related to bad coding practises and sloppy style.  (For example not fastidiously unsubscribing to events when you're finished with them). Prevention is always better than an ambulance at the bottom of a cliff for sure.  Obviously though, no one is perfect and mistakes will be made, get through peer review and be checked in.

It is surprising though how good the GC actually is, I'm certain that there is loads of sloppy code checked in all the time and more often than not the GC does a better than fair job cleaning up. Isn't managed code grand, allowing us to spend more time writing product. ;-)  Sometimes though, it is going to be unable to detect an object or graph of objects are no longer needed.

When this happens you need to be able to profile what is going on a great detail inside memory and the GC.
SOS.DLL is an assmebly provided by the .NET framework for this purpose exactly. Check out this article on Code Project to find out how to use it.

Thanks Marjorie.

WCF Asynchronous Services

During a design session the other day someone was asking what are the possibilities for asynchronous calls in WCF.  There are are number of ways to do it, each with different attributes.

  1. When referencing a standard WCF service from the client using the advanced options (of the Visual Studio add service reference dialog) you can generate BeginInvoke and EndInvoke methods. This allows for an "IAsyncResult invocation pattern" (check out MSDN - Invoking synchronous methods asynchronously and good article on Code Project explaining asynchronous calls).  Essentially you pass in a call-back that will be called when the method returns, and they you are able to retrieve the method result from the IAsynResult argument provided. This gives a clientside WCF service consuming developer the option to execute standard synchronous WCF services asynchronously. Great if you do not have control over the service. Also ideal if the expected delay between request and response is not larger than 60 seconds or so.

  2. A standard WCF service can be decorated with IsOneWay=true in the OperationContract attribute. This effectively tells WCF to immediately return the thread back to the caller.  No return values or response is possible from such a service, including exceptions. These are fire and forget style services (sometimes called Document Services).

  3. The most advanced and flexible way is using Callback Contracts. This requires another Contract be defined and specified with the requesting ServiceContract. Also known as Duplex services.  Usually the Operations are also decorated IsOneWay=True, indicating that the calling thread is released back to the client immediately.  These are ideal when writing a publish/subscribe pattern and the response will be sent back to the client at some future point at an unknown time. It could be minutes or hours, or it could generate 100 responses over time for one "subscribe" request. Its almost like an event subscription.  See the MSDN article referenced below for more info.
    *EDIT* I would recommend avoiding using this pattern if possible, a far more robust way of achieving the same results without resorting to Singletons is using MSMQ.  A common way to deal with long-running Duplex services is to make them singletons to be able to store the callbacks.  You can avoid this by create a class to manage the callbacks, but then this class effectively becomes a singleton.  A far simpler pattern is to take advantage of MSMQ.

Its also worth noting that when searching for Asynchronous method and service invocation patterns the Reactive (Rx) framework seems to come up a lot.  This was a framework that was pioneered by a team at Microsoft to "clean-up" code that needs to call methods asynchronously. Its kind of like Linq over Events, and they succeeded in making calling code more elegant.  However it has been superseded by the Task Parallel Library (TPL) in .NET 4, more specifically the Task Factory and associated classes.  Some say this is not so, but essentially in my humble opinion what can be done out of the box in .NET 4 without an extension framework is the best way to go.


Sunday, May 1, 2011

Professional Motivation

Here's a great short you-tube video recommended to me exploring the idea of modern professional motivation.  Money not only is a bad motivator, it actually delivers worse performance once people are paid well already. So what should company leaders use to motivate their staff?