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!).

64_bit_operation_taking_long_time

VS2012_test_debug_error

Solution
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.

Project_properties

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

Posted in ReSharper, TDD, VS2012 | Comments Off on VS2012 ‘Cannot launch debugger’ error when trying to debug tests

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 | Comments Off on WCF error-handling strategies (part 2): Throwing specific fault exceptions

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 () {
$(“input[type=text]”).first().focus();
});
</script>

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 | Leave a comment

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 | Leave a comment

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 | Leave a comment

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.

ChannelFactory<T>
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 | Leave a comment

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 | Leave a comment

TDD and the Red-Green-Refactor approach

We’re all familiar with the term test-driven development now, but it seems a lot of developers still aren’t using it in their normal daily routine. TDD has been in circulation since 2003 or earlier, and has probably been mainstream since 2005. But I’ve worked at companies and spoken to developers at other firms where they admit that they still don’t really follow the test-first approach (and was guilty of it myself when I first started out with unit-testing).

Test-driven (or test-first) development is a whole new mindset and a discipline which you need to practice quite a lot before it becomes second-nature. At first it seems cumbersome and slow, especially when time is precious and the clock is ticking. So the temptation is that you write the implementation first and then write your tests afterwards and make sure they pass. No one will ever know, right? And surely it took the same amount of time as if you’d written it test first?  Or possibly even quicker because you’re already familiar with the code that’s being tested?  Well apart from breaking every rule in the TDD handbook, maybe you’d be surprised to find that it probably took longer than if you’d written it test first.

To explain, here’s a summary of TDD red-green-refactor development (by the way if you’re not from a testing background, red and green refer to a test framework GUI runner such as NUnit where tests that pass are displayed green and tests that fail are shown in red).

1. Red: Before you write a single line of code, you need to be familiar with the requirement you are about to satisfy. If not, there’s no point starting – how will you ever get the desired end result?  The days of hacking out code in the vain hope that by the laws of probability, you might eventually get it right are well and truly over. But in an ideal world you will hopefully have a user story you are familiar with and a particular task you’re supposed to be working on. So once you have a clear idea of what it is you are trying to achieve, write your test first and run it to see that it does actually go red (you may need to stub out the class and method under test before it will compile, but this is OK). You have now achieved two things: you have an automated test which will ensure the integrity of your software over time, and it also describes the client requirement. As such, it documents the expected behaviour of the software which will be invaluable for  maintenance over the coming weeks/months/years of the software’s lifetime. By writing the test, it proves (assuming you’ve got it right of course) that you understand the business requirement.  And if not, it proves that you didn’t understand it!

2. Green: Now you have a test in place, you can write the code to make the test pass but only write enough code just to make it pass and nothing more. Time = money and no client has ever been happy when software is delivered late. If the test passes, then that requirement has been satisfied and you can move onto the next task (or next user story). Don’t waste time messing around with code if your tests are all green. In the long run this tactic will save you a lot of time and is key to working in an Agile manner.

3. Refactor: Finally (and only if you are running ahead of schedule and have time spare) you can refactor code where the tests are already green. And then – most importantly – re-run your tests to prove you haven’t broken anything. But remember, you’re not doing this for the client’s benefit. You are doing it for your benefit but at the client’s expense. If you go back to a client and tell them that you’re behind schedule because you spent two days refactoring code that was already working, they’ll probably fire you on the spot! OK, maybe not anything quite that drastic but you certainly won’t make yourself very popular.

As developers we always need to justify how our precious (and expensive) time has been spent, so spend it wisely. We are all providing a service to our clients and this means that doing what’s best for the client takes priority over what’s best for us. And delivering working software on time is what they really want, not software that’s beautifully refactored but cost twice as much to build (and ultimately still does the same job it did before the refactor). I’m not suggesting that you start writing unmanageable code which just happens to make your tests pass. But you need to find the right balance between correctly functioning software which may not be very pretty but gets the job done, and correctly functioning software which has had hours of refactoring work spent on it while other areas of the system remain unfinished or have defects. So hopefully you will start writing your tests first and keep your clients happy.

Posted in Agile, TDD | Leave a comment

Generating WCF service proxy classes using SvcUtil

There are various ways to make calls to a WCF service from client code but this particular example uses the Microsoft svcutil.exe proxy generation tool. This is most appropriate when you want to consume a third party service and don’t have access to the service contract type declarations, but you can obtain a service metadata WSDL document from the service. To check if service metadata exchange (mex) is enabled, browse to the service and put a ?wsdl query string parameter at the end of the URL path. If it returns a WSDL XML document in the response, then metadata is enabled and you can use SvcUtil.

However, if you do have direct access to the service contract declarations (e.g. via a shared assembly) then I recommend using the WCF ChannelFactory<T> class instead of using svcutil.exe because it makes life a lot easier (see my post on how to use ChannelFactory to create re-usable proxy classes).

The following example is based on a WCF web application project using HTTP binding, but it would work just as well with a self-hosted service using another transport such as TCP.

Example service
I’ll start with a simple WCF service contract with a single operation called RegisterUser. The ServiceKnownType attribute is used to tell the WCF data contract serialiser which concrete type (in this case UserRegistration) implements the IUserRegistration interface. I haven’t shown the service implementation here, but you can just assume that it exists. Generating service proxies is all about the service contract (interface) – not the service implementation.

The UserRegistration type is a simple DTO (data transfer object) used to transfer data between a client application and the service. The DataContract and DataMember attributes which decorate the class enable the WCF data contract serialiser to convert it to and from XML.

Generating the service proxy
So now we have a service and data contract class but how can the client access them? One option is to use the .NET service model metadata tool svcutil which will generate the necessary proxy code and service configuration for us. Among the many command line switches that are available for svcutil, you can specify a namespace for the auto-generated proxy types. This is a great help in differentiating between types which are defined in the service layer when you are using them in client code. One important point about svcutil is that it should be run using the Visual Studio command prompt. Your service also needs to be hosted on IIS, IIS Express (Microsoft WebMatrix) or Cassini (Visual Studio development web server) before you can generate proxies. To ensure the service is hosted properly, try browsing to the service URL before attempting to generate the proxy.

Below is an example svcutil command line. I recommend using a fixed port number for WCF web application service host projects during development, so that you can add svcutil command lines to a batch file which can be re-run each time a service contract changes. To set a fixed port, go to service host project Properties > Web > Specific port, and enter a port number of your choice which obviously doesn’t conflict with another port in use in your solution (or within the system you are working on).

svcutil.exe http://<service url>?wsdl /t:code /n:*,Example.Client.ServiceProxies

Note the command line specifies a namespace Example.Client.ServiceProxies via the /n switch. There are additional command line switches to specify the output directory path, config file name, etc, but I have tried to keep this example as simple as possible for now. I recommend you look at Microsoft’s documentation for svcutil on the MSDN website and try out the other command line switches which are available. However the ones I’ve found most useful are:

/n:*,<namespace>  – Namespace which will apply to all generated code (and also appears in the service contract config). If you don’t specify a namespace on the command line, all generated code will belong to the global namespace which trust me, will come back and bite you when your client types and service types all become indistinguishable. Especially in your integration test projects where you will end up in project reference and type name conflict hell. The * parameter means all types will be included under the same namespace.

/d:<directory>  – Destination file path for the generated output. This is really useful for outputting the proxy code and config files to a specific location in your solution folder structure (e.g. a folder in your client project). However if several projects in a solution need the same proxy files such as a client app and a test project – which is a common situation – then direct the output to a shared folder and add the files to different projects as a link (Add > Existing Item > Add As Link).  This will prevent multiple copies of the same file being scattered throughout your solution.

/config:<config file name>  – Specific name for the generated .config file. By default it’s called output.config but obviously if you are generating proxies for more than one service in the same location, the output.config files will overwrite each other which is not very helpful. If I want separate config files, I usually specify the same name as the service, e.g. AccountService.config.

/mergeConfig  –  Rather than having a separate config file for each service, you might want all config output to a single file. This is what the /mergeConfig switch does. You can still use this together with the /config switch to specify the name of a single config ouput file for all services.  Or you can specify the name of an existing config file you want the WCF configuration to be written to (e.g. the Web.config of a web application).

Automating proxy generation
Every time a service contract or data contract interface changes, you will need to regenerate your proxy files. This can get pretty boring after a while and you don’t want to keep typing out command lines by hand because it’s slow and error-prone. So create a batch file containing the svcutil command line for each service (either all in the same batch file or separately – it’s not important) and add to your solution. I usually create a solution folder called Scripts and add all my batch files to that. Simple automation like this will save a lot of wasted time and mistakes in the long run and it also means the batch file can be added to your source version control system which is important. Every time you find yourself typing out the same thing again and again, automate it and get it under source control.

Adding svcutil output to your client project
When you run the svcutil command, it generates two files. The first is a code (.cs) file containing proxy classes for the service and any types decorated with the [DataContract] attribute which will be automatically serialised. The second is a config file containing the WCF service endpoint configuration you will need to communicate with your service. Simply add the code file to your client project in the same way you’d add any other class  file. I usually add a new folder to my client projects called something like ‘ServiceProxies’ and add the autogenerated proxy code files to this folder to stop them cluttering up the project (if your client app is using several services, then you will have separate proxy files for each one so keeping them grouped together in folder like this is a good idea).

Be aware that whenever you add a WCF service proxy file to your client project for the first time, you will also need to reference the System.Runtime.Serialization and System.ServiceModel assemblies before the client project will compile. I think the names of the assemblies make it pretty self-explanatory what their purpose is. System.ServiceModel is the core service library containing WCF types and System.Runtime.Serialization is required for data contract serialisation and deserialisation over the wire.

Next, you need to add the auto-generated service configuration to your client’s app.config or web.config file. If the client project is not a web application and doesn’t currently have a config file, then simply add an application configuration file to it. Regardless of whether it’s an app.config or web.config, the process is still the same. Copy the entire <system.serviceModel> section from the auto-generated service config and insert it into the <configuration> section of your client’s .config file. It doesn’t matter where it goes but I usually keep all my service config below existing configuration sections to stop it turning into an unreadable mess (which XML config can do very quickly).

Calling the service
The auto-generated proxy code and service configuration will both use the namespace you specified on the svcutil command line. So in this example, the UserRegistration data contract class will appear as Example.Client.ServiceProxies.UserRegistration in the client code even though its real namespace in the service layer is Example.Services.DTO.UserRegistration. This prevents any confusion, making it crystal clear to everyone that this type is a proxy of a type actually defined in the service layer.

Now to call the service from the client app, simply use the auto-generated service proxy class which will have the same name as your service but with a ‘Client’ suffix. So in this case it’s called AccountServiceClient.

When used in combination with the service configuration (which contains the address and binding responsible for creating the channel stack) the proxy will automatically marshall the call across to the hosted WCF service. As you can see, once the proxy classes and configuration are in place, the client code needed to call a service is very trivial.  This is a far cry from the difficulties of older messaging technologies and shows just how much WCF has made things easier from a developer’s perspective.

I describe how to solve compiler errors when sharing data contracts between multiple services in this separate post.

Posted in Automation, C#, WCF | Leave a comment

Keeping domain models and view models separate with ASP.NET MVC and WCF

The location, role and responsibility of objects within a software system is a common topic in the forums with plenty of disagreement about what is and isn’t correct. But first, let’s just define some commonly found objects and their roles:

Domain repository entity: Object which is an in-memory representation of a record persisted in some sort of backing data store. In most business scenarios, a repository entity will be mapped to a physical database table via an ORM tool such as NHibernate or the Microsoft Entity Framework. 

Domain model entity: An object which lives in the service layer and typically contains both logic and/or data. This is where your business rules should be defined. Often, a domain model entity and a domain repository entity will be the same thing. In other words, an object which contains business logic and is also mapped to a data store (e.g. an Order domain entity may be mapped to an Order database table, but also contains business logic to calculate the total cost of the order, including tax). This arrangement allows data to be processed by business code and persisted via the same object.

Data contract: This is a DTO (data transfer object) which is decorated with the WCF DataContract attribute. This is essentially a ‘dumb’ object containing just data and no logic, and is used to pass data across service boundaries via serialisation. Data contracts will usually by mapped to domain models to copy data from one to the other.

View model: Another type of DTO but limited to just the MVC UI layer. View model objects are used to pass data between MVC controller action methods and the views which display and capture model data.

Passing data between services and the web UI
So with these definitions in mind, it is OK (and necessary) for data contracts which are defined in your WCF service layer to be passed to and from your MVC web application. However for this to be possible, the MVC web app must have access to the data contract type declarations. The way you achieve this is to always have your WCF service implementation and WCF service & data contracts in separate assemblies. Then from your MVC web app, you can reference the project/assembly containing the service & data contracts (but do not reference the service implementation assembly).  Now your MVC web app can happily use data contracts defined in the service layer, and will still compile.

However it’s not OK for domain entities to be passed across the same service boundaries because then you blur the line between what should be a simple data transfer object and something containing logic which should never be directly exposed to your MVC views and controllers. Ignore this at your peril otherwise you will end up with business logic contaminating your UI layer which will lead to no end of problems in the future and result in a lot of refactoring and maintenance.

But how do you keep them apart?  Well from a coding point of view, one approach is that only classes that have absolutely no business logic should be decorated with DataContract and DataMember attributes. This prevents serialisation of domain entities meaning that they can’t accidentally or intentionally be used as a parameter in service contract. Another more basic check is to make sure that the web UI project never references an assembly containing domain entities (sounds obvious but I’ve seen it happen). This will keep them safely isolated from the UI. However from a physical point of view, the simple answer is that you can’t absolutely guarantee this won’t happen. It only takes one developer to unwittingly do the wrong thing and the rot starts to set in.

So if you can’t physically keep them apart, what can you do to contain the problem?  Well you have to rely on some fundamental development techniques which have been around for years: discipline, team communication and code reviews. OK I’m not going to win any awards for innovation here, but building a reliable system is more than just writing a lot of tests and then assuming everything’s OK. You have to enforce design rules and best practices which the development team sticks to, and the appropriate use of domain entities, view models, data contracts, etc. is all part of that.

Passing data within the UI
Any application with an MVC web client and WCF services will reach a point where types defined in the service layer and types defined in the web UI meet, and in most cases that will happen in your MVC controllers. But for most scenarios, that’s the only time they will share the same space. It will also help if you give data contracts and view models different names. View model names typically should reflect the view they relate to, and I usually add a ‘Model’ suffix to them for clarity (but it’s down to personal preference how you do it). However if you are using the SvcUtil tool to generate service proxies, I recommend you specify a namespace so that it’s clear which models are defined in the service layer (see this post for generating service proxies).

In a typical case where you need to get data from a view model object into a data contract object so that it can be sent to a service, all you have to do is map the properties between the two via an object initialiser, in a constructor, or using a mapping tool such as AutoMapper, although AutoMapper can be quite hungy on memory resources so be aware of this when you decide what to use. Writing your own mapping code is trivial so why use anything else?

There’s a bone of contention about whether data contracts defined in the service layer should be used as view models. Personally I don’t have a problem with it and actually prefer to have my view model types declared as data contracts in the service layer rather than in the MVC app. This is so I only have to define data annotation validation rules once rather than defining them against data contracts in the service layer, and then again for  view models in the MVC application. This makes unit/integration testing easier and reduces the chance of a property not being validated properly. As a result, data contracts declared in the service layer are passed directly into my views (so there are very few actual view models declared in the MVC app).

However you may not like this and prefer to have separate, dedicated view models because it avoids the situation where views end up being strongly-typed to classes defined in a different layer of your architecture. How you do it is entirely down to person choice.

Posted in Architecture, ASP.NET MVC, WCF | Leave a comment