VS2012 ‘Cannot launch debugger’ error when trying to debug tests

If you’re using Visual Studio 2012 with ReSharper on a 64-bit version of Windows and get these messages when trying to debug a test, this is a known issue with Microsoft VS2012  and not ReSharper (so don’t go blaming the guys at Jetbrains!).



Even though there have been several updates for VS2012, this issue still hasn’t been fixed.  However there is a simple workaround which will get you up and running again. For each of your test projects, go to project Properties > Build and change Platform target to x86.


Now build the test projects and try again. This time it will let you debug your tests as normal.

Posted in ReSharper, TDD, VS2012

WCF error-handling strategies (part 2): Throwing specific fault exceptions

(See WCF error-handling strategies part 1 here)

Deciding on the right error-handling strategy for your WCF services and clients can be tricky. But if you’re not 100% clear on exactly what strategy you are using and how it will behave under different situations at runtime, then you may be in for some nasty surprises later on (especially if your code has already been deployed to a production server). So plan it and implement it from day one.  Do not leave it as a ‘TODO’ task on your whiteboard.

I have tried various different approaches and the one that seems to work best is for WCF contracts to explicitly declare the types of FaultException<T> that a service operation may throw. This way, clients are fully aware of what exceptions to expect and can add the necessary exception-handling. This spreads the responsibility somewhat – it is down to the service developer to keep service contracts up to date with any new types of FaultException<T> that are thrown. And it is down to the client developer to put the required exception-handling in place. Of course, good integration test coverage will ensure there are no leaks on either side of the messaging boundary so always update your tests as new exceptions are added.

Service Contract
Declaring the types of FaultException<T> that a service operation may throw is done via the FaultContract attribute as shown below.

Service contract

In this example, CreateAccount may throw an exception of type FaultException<ValidationFault>,  FaultException<GeneralFault> or just a plain non-generic FaultException (which you obviously don’t have to declare in the contract as it is the default WCF exception type). ValidationFault and GeneralFault are just example custom fault types which indicate to the client application what went wrong, but you can replace these with any fault type you like.

Client Exception-Handling
Faced with the example service contract above, the client developer should then provide the following try-catch block to cover all possible outcomes. I haven’t included the code to call the service because that’s covered in other posts. But what really matters is that it’s done within the try block and there are matching catch blocks for each expected exception. Depending on the type of client you are developing (web/desktop/mobile app) you may have global exception handling, or you may surround every service call with a try-catch block, or you may have a helper delegate which catches all exceptions. Exactly how you do it is up to you, so long as it’s exception-safe otherwise your client app could start displaying unwelcome error messages or worse still, crash.

Client exception handling

As with all client/service messaging, the actual service calls should be made via a proxy (see this post for more information on developing WCF proxies).

Service Fault Types
So you have your service contract and client exception handling worked out. Now you need the actual fault types which will be passed to the FaultException<T> constructor in your service layer. To make this easier, here is an abstract base fault class which will also act as a helper to create the strongly-typed FaultExceptions. Notice that it is decorated with the DataContract attribute. That’s because the derived fault types need to be serialised by the ServiceModel DataContractSerializer, otherwise message serialisation would fail.

Fault class

The static Throw method instantiates a strongly-typed FaultException based on the type of Fault you give it, and throws the exception.

And here’s an example of a concrete fault class, derived from Fault, which you might throw if input validation fails in your service (e.g. the user enters an invalid email address).  This class has been kept very simple because fault classes should provide the minimum amount of information a client needs and no more. A message explaining what went wrong is usually sufficient, which is exactly what the base Fault.ToString method does. All technical details such as exception stack trace should be kept hidden from the client and logged server-side. You don’t want to reveal the intellectual property and technical details about your services to customers or potential hackers.

Validation fault

Throwing a fault from the service
Now raising a specific exception from within your service layer is very straightforward as shown in the following example which assumes email validation has just failed in some previous line of code.

Example usage

Most importantly, don’t forget that the fault messages you put here could and most likely will end up being displayed on-screen to your users at some point, so always make sure the grammar, punctuation and spelling is correct. Don’t spoil good software with amateurish user messages. This is just a simple example but for globalisation purposes, you would probably want to keep fault messages like this in string table resource files or a database rather than hard-coding them.

One final note – you can add automated WCF parameter validation to your services by referencing a NuGet package such as WCF.Validation.Engine which sets model state validity in a very similar way to how MVC view model validation works, but that will require a whole separate post!

Posted in C#, WCF

Automatic page element focus in MVC

It’s really annoying when a web page doesn’t have focus set to an element on the page by default. Especially for things you visit regularly like login pages. It shows no effort went into the design or UX.  So here’s a nice little trick to automatically set focus to the first textbox element on every page in your MVC site. Just add the following block of javascript to the HTML header section of the _Layout.cshtml, or whatever your chosen MVC 3 layout file is (in MVC 2, this will be the view master ASPX file).

<script type=”text/javascript”>
$(function () {

This short but effective piece of jQuery script is executed every time a page loads, selects all text input elements and sets focus to the first one it finds.

Posted in ASP.NET MVC, Javascript, jQuery

WCF error-handling strategies (part 1): IServiceBehavior and IErrorHandler

Probably the biggest of all cross-cutting concerns is error-handling and logging. Unfortunately, WCF doesn’t seem to have a silver bullet for capturing, logging and suppressing exceptions thrown in the service layer. Ignoring Windsor interceptors for the moment (which deserve a separate post of their own) you really only have two options: put a try-catch block inside all of your service operations – which becomes very tedious very quickly –  or let your services throw exceptions and catch them in the code which consumes them. Initially I went for option one but it’s too prone to human error. If you or another developer forgets to put a try-catch block inside one of your service operations it could potentially bring down a client app. Or at the very least, error information will be lost making it harder to identify the problem.

As I found out, it’s actually quite difficult to stop WCF services from throwing exceptions. So like it or not, the better option is to actually let your service throw errors back to the client application, which should be ready to deal with them. At least this approach of ‘expect the worst case scenario’ means there won’t be any nasty unpredictable situations or crashes on your production servers if errors do occur, because you should have already catered for them.

The standard FaultException
When a System.Exception is raised in the service layer and no matching catch block is found, the ServiceModel converts it to a System.ServiceModel.FaultException before re-throwing it. This is problematic for two reasons. Firstly, it doesn’t give you an opportunity to log the error before it’s thrown (the client may be a third party so you need to maintain your own error log) and secondly, the standard conversion to a FaultException is next to useless because the original error information is discarded.

Here is a standard FaultException message which doesn’t tell you anything about the error that actually caused it:

System.ServiceModel.FaultException: The server was unable to process the request due to an internal error. For more information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing as per the Microsoft .NET Framework 3.0 SDK documentation and inspect the server trace logs.

On the subject of what this exception message recommends, it’s OK to enable the IncludeExceptionDetailInFaults attribute in the config during development, but you should never do this on a production server. So that doesn’t solve the problem.

The Solution
The solution to getting useful server-side logging and not losing error information during conversion to a FaultException is to implement the IServiceBehavior and IErrorHandler interfaces. IServiceBehavior allows you to implement a service behaviour attribute which takes a custom error handler parameter which implements IErrorHandler. Whenever an unhandled error occurs in a service decorated with the service behaviour attribute, two methods on the custom error handler are called automatically: ProvideFault which allows you to construct a FaultException (rather than let ServiceModel do it), and HandleError which is intended for logging. The ProvideFault method is called first and HandlerError is called asynchronously on a separate thread, so lengthy logging operations don’t block the service request thread from sending a FaultException back to the client immediately.

Here is a standard implementation of IServiceBehavior which is completely reusable and should be put in an infrastructure assembly so that it can be shared between different projects/solutions. As you can see, it instantiates the specified error handler type using Activator.CreateInstance, adds it to the channel dispatcher’s error handlers collection and that’s basically it.

And here is an abstract base class implemention of IErrorHandler which again is completely reusable and should go in the same infrastructure assembly. The most important thing here is that the original exception information is added to the fault message rather than being discarded.  If third parties call your service, you will probably want to return a more cut-down version of the original exception which doesn’t include security-sensitive things like the exception stack trace.

Now all you have to do is implement CustomErrorHandler with a specialised error handler for your service. How and where you log error information to (file, event log, database, logging service, etc.) is up to you. And remember this is called asynchronously so don’t be too concerned if logging isn’t instantaneous – it won’t delay the FaultException being thrown.  And the class is non-static and stateless so there are no multi-threading issues to worry about as long as you keep it that way.

The final step is to decorate services with the ErrorBehaviour attribute and the type of your specialised error handler.

All unhandled exceptions will now be caught and processed by your error handler, before being re-thrown to the consumer of the service. This means you will always be able to (a) log any errors, and (b) control what error information is, or is not sent back in the FaultException message.

See the follow up post on throwing specific fault exceptions here.

Posted in C#, WCF

How to avoid changing your WCF service contracts

WCF service contracts are like legal contracts. Once released, they are set in stone and should never be broken. If there are client applications which consume your service and you decide to change one of the operation signatures on the contract, it will break the clients because they were built to use the original contract interface. So the only option you have is to add additional methods to the contract while leaving the original interface members intact. This is the Open/Closed principle (the ‘O’ in SOLID) – open to extension but closed to modification.

However over time, such extensions can lead to badly designed interfaces. Because WCF services don’t support operation overloading, you might have multiple similarly named service operations which take different parameters for what is essentially the same method. This isn’t a good situation to be in, and over time your once clean interface will turn into a confusing mess. I once had to write an application which used commercial third-party financial services with the most appalling interfaces, because they had so many different versions of the same method. It was a nightmare, so don’t do this to your clients!

To avoid going down the path of interface bloat, you need to get into the habit of using specific request and response types in your service contracts right from day one. Here’s an example of a service contract before and after doing this to show how much it is improved.

Inflexible contract
Here’s the first draft of the service contract, with a single operation which takes a data contract called User and returns a boolean. No surprises so far.

And the service which implements the contract:

And here is the data contract passed in as the parameter:

So far all very basic stuff. I finish coding the service, deploy it to my production server and all of my clients immediately start using it. Job done. But before getting too pleased with myself, I  suddenly realise that I can’t return specific information to the client application if registration fails (beyond a simple true or false). So clients have no idea what actually caused registration to fail. And worse still, I realise that I don’t actually want to pass in a User type anymore, but a UserRegistration type which contains more properties. Here we go down the path of expanding contracts already. But it doesn’t have to be this way…

Future-proof contract
So here is an improved version of the service contract which avoids these pitfalls. But before going into detail, just one point about returning error information. Although the original interface only returned a boolean, you could in theory pass back detailed error information back to the client. However this is not recommended outside of the development environment, especially if your service is going to be used by a third party. You absolutely don’t want third parties seeing an exception stack trace ever because it contains specific details about your code and infrastructure which should remain hidden for security reasons.

It’s only a minor change, but the operation now has dedicated request and response types which are obviously both data contracts:

Below is the implementation of the new service contract. In this particular case it prevents exceptions being thrown, and instead wraps success or failure status together with any error information in a response object which is returned to the client.  I have included a try-catch block in this example just to demonstrate returning different response values. But in reality, you don’t want to be adding a try-catch block to every new service operation you create (what if you or another developer forgets?). So a better alternative is to use custom error handlers, or intercepts or policy injection via the Microsoft Enterprise library. This allows features such as exception handling, logging, etc, to be automatically added as a wrapper around the service messaging pipeline. And once the infrastructural code is in place, you can forget about it. However this is a whole separate subject so I won’t use it in this example.

This is the new request data contract. In this particular scenario all it’s doing is wrapping our original User type, but the point is that additional data members can be added over time without having to ever change the service contract itself.  Only the data contracts change.

This is the real power of this approach to service contract design. The contract remains the same but it’s the data contract parameters which are extended whenever the service needs to receive or return additional data. It also promotes very clean simple contract interfaces because no matter how much data you pass in, you only ever have a single request parameter.

And here is the response data contract together with its base type and status enum. The response type could have any number of data members added to it, but notice how the base response provides two essential properties which tell the client (a) if the service call was successful, and (b) if not, then one or more messages indicating what failed.

The base response provides everything we need for this simple example so RegisterUserResponse doesn’t actually have any data members of its own, but again it may be extended in the future without changing the contract. And don’t be tempted to use the base response as the return type in your contracts. Always use derived request and response types specific to each particular operation, to guarantee future-proofing your service.

Using this approach to service contract design will greatly reduce the risk of you ever having to alter a service contract once it’s been published.

Posted in Architecture, C#, WCF

Creating a WCF service proxy with ChannelFactory<T>

Before going into the details of using ChannelFactory, if you are not familiar with service proxies (or have used them but don’t understand why they’re important) here’s a little bit of background. When a client application makes a call to a service, it shouldn’t know or care  about the implementation details or physical location of the service. All the client should be aware of is that there is an object which provides some useful functionality. Everything else about the service should be hidden away.

And this is exactly what a proxy does – it hides the technical details of the service from the client by adding an extra layer in between. The proxy object exists in the same memory address space as the client and marshals calls across to the service on the client’s behalf. The service could be a WCF service with TCP bindings which is hosted somewhere on the same local area network as the client, or it could be a RESTful HTTP service hosted in the cloud on the other side of the world. It simply doesn’t matter. All the client needs to know are the details of the proxy. The service which sits behind the proxy is effectively invisible.

This is good software design and ensures your clients and services remain loosely coupled and are therefore easier to maintain. If there are any physical changes to a service (e.g. a newer version becomes available which just happens to be implemented in a different technology) it is the proxy that will change, not the client. With any luck, you shouldn’t have to touch the client code at all. However avoiding changes to the client is less easy if the interface to an existing service changes. I describe how to minimise the impact of changes to service contracts on the client in more detail here.

Using the ChannelFactory<T> class to make calls to your WCF services is an easier alternative to the laborious process of generating proxies via the SvcUtil tool every time a service contract changes. As its name suggests, ChannelFactory is a factory for creating service communication channels at runtime. This means no matter how often your service contracts change, you won’t have to manually re-generate proxy classes or alter client-side service model config each time.

ChannelFactory<T> takes a generic parameter of the service type you want to create a channel for (this must be the contract interface). And as an absolute minimum, it requires a specific binding and endpoint address. You can supply additional information, but this is enough to achieve a remote connection to the service.

Because ChannelFactory only requires knowledge of the service contract, it makes good design sense to put your service/data contracts and service implementations in separate assemblies (never put your service contracts and service implementation in the same assembly). This way, you can safely distribute contract assemblies to third parties who wish to consume your services, without the risk of disclosing their actual implementation.

Example usage
As an example, here’s a very basic service contract. To keep things simple, I haven’t used any data contract parameters but if there were any, the data contract type declarations should be included with the service contract interfaces in the same contract assembly. This is so that you can share the contract assembly with other solutions or distribute to third parties (otherwise clients won’t be able to instantiate the parameter types).

Here is the service implementation.

And here is the client-side code to call the service using ChannelFactory<T>.

As you can see it’s surprisingly simple. It doesn’t look like much but we are still supplying the essential ABC requirements of WCF. A is the address of the service endpoint, B is the binding (in this case I’ve used basic HTTP binding because that is the default service binding – client and service bindings must always match), and C is the contract interface. You don’t need any more than this to achieve a service connection. At this point you are probably wondering why you’ve spent so much time messing around with complicated client-side WCF config!

A reusable proxy base class
But as I explained earlier, you don’t want this sort of infrastructure code dotted throughout your client applications. It should be wrapped in a service proxy class. You also don’t want boilerplate service code duplicated over and over again in different proxy classes, so here is a generic base class to take care of the specific details of creating a channel. If you don’t already have one, create a WCF infrastructure assembly and add the proxy base class to it for future reuse with different solutions.

Notice that the base class is thread-safe – a crucial but sometimes overlooked issue with server-side classes. Also notice for the sake of clarity, I omitted the region which implements IDisposable which is shown below:

You could also extend the base class constructor to take different bindings, etc, but I’ll leave that down to you. Now to see this in action, all you need is a concrete proxy class which is strongly typed to your service contract:

Notice that the proxy class name is the name of the service but with a ‘Client’ suffix. This is a standard WCF naming convention which you should follow so that other developers will immediately understand its purpose.  Also notice how the GetMessage method is simply a wrapper for a call to the GetMessage operation exposed by the service contract, but the client has no knowledge of this. All it knows is that it calls a local method and gets a return value.

Wrapping it all up
Finally, put the concrete proxy class in its own service proxy assembly (don’t be tempted to just add it directly to a client project). Having the abstract base and concrete proxy classes in separate assemblies will promote reuse with different client applications and across different solutions meaning you and other developers will be able to use these assemblies straight out of the box when they need to communicate with the same service.

And here is the revised client code which now calls the service via the proxy:

See how simple this has become compared to the original client code earlier which called ChannelFactory<T> directly?  I have included a service endpoint URL in this example but even that would be hidden away in a config file in a real application, so the client really is achieving quite a lot through some very minimal code.  This will keep your client code clean and simple, speed up development time in the future and reduce maintenance costs.

Also see the follow-up post how to avoid changing WCF service contracts which describes good contract design.

Posted in Architecture, C#, Multi-threading, WCF

Resolving data contracts shared between multiple WCF services with SvcUtil

If you’re using the SvcUtil.exe tool to generate proxies for WCF services, before long you may hit a problem where the same data contract shared between two services results in a compiler error at the client. You could just specify a different namespace for each service proxy but then you’ll have exactly the same data contract type defined under separate namespaces which is a rather clumsy solution. You could also use the /excludeType switch, but you still have to remember which service should and shouldn’t be exporting a particular type which again isn’t ideal, especially if you have a lot of data contracts to filter out.

The problem
When you decorate a type with the DataContract attribute and use it as a parameter in a service operation, SvcUtil will automatically generate a declaration for that type in the proxy code file which it outputs. This is obviously so that a service client can instantiate the data contract type client-side, and use it to receive and send data to the service (via message serialisation). So far so good. The problem occurs when you have a data contract in a common assembly which is shared between several services, because the data contract will be declared in multiple proxy code files as shown below. When you try to compile the service client, it complains because the same type is declared more than once.

The Solution
The way to solve this without messy namespace workarounds relies on you having access to the same shared assembly which contains the data contract declarations used by the services. Specify a reference to the shared assembly in the SvcUtil command line using the /reference (or shorthand /r) switch:

svcutil.exe http://<your service url>?wsdl /t:code /reference:<path>\CommonAssembly.dll

This tells SvcUtil to generate the proxy code file without including a declaration for the data contract on the assumption that the client will then reference the shared assembly directly to make the data contract type declaration visible.  This way, the data contract can be used in multiple places but only declared once.

This diagram shows the logical relationships between the shared assembly, the client and the services. But obviously in a real deployed environment the client would have a separate copy of the shared assembly. Unfortunately if you don’t have access to a copy of the shared data contracts assembly used by the services, then this solution will not work for you and you will have to specify different namespaces on the command line using the /namespace switch, or exclude data contracts from all but one service using the /excludeType switch (or some alternative means).

As a final design point, your WCF service implementations should be contained in one assembly, the service (.svc) files should be in another, and finally your WCF service contracts and data contracts should be in a separate assembly of their own. By doing this, it makes sharing service and data contracts between different services and client applications very easy and avoids exposing service implementation details to the client.  Never put implementation and contracts into the same assembly because you seriously limit the flexibility of your application architecture. Divide and conquer.

Posted in WCF