WCF by Example - Introduction

Patterns and best practices for the desing and development of rich client enterprise applications using WPF, WCF and NHibernate

Chapter I

Latest modifications

New on 28th May 2013:I submitted an article on the Azure Contest at LiteDispatch - Logistic solution on the cloud[^] In this article I am using the same patterns covered in these series. But a different aspect is that this is an example of an MVC 4 application that uses EF Code First; it discusses how to integrate an MVC application in AzureWebSites using SQL-CE and then it covers what it takes to get the application running on Azure SQL Server. It also contains interesting aspects like EF Migrations and a discussion on hybrid persistence configurations where two EF contexts are set to run within a single application. One connected to SQL-CE and the other to Azure SQL Server. As well, the project is a working example of the Simple Membership using EF Code First and SQL-CE. The application can be found at http://litedispatch.azurewebsites.net/[^]

The source code for the articles is located at its own project in Codeplex, latest changes can be found at the trunk branch.

In Feb 2013 EF support was added to the solution, I used EF Code First and SQL-CE.

In Dec 2012, RavenDB support was added to the solution.

In Oct 2012, the solution was amended so NHiberante is also configured to work with SQL-CE 4.0; previously it was only working for SQL Server or the Express versions; you may want to check it out to see what it takes to get your application running using SQL-CE and NHibernate.

In Dec 2010, the server side of the application was deployed to Azure, a ready-to-run client is available on codeplex. The WPF client can invoke
methods to a WebRole deployed in Azure. This source code can be found at CodePlex at eDirectory.WPFClient.Azure.zip

Introduction

This article is the first of a series that discusses how to design and develop a
WPF client using WCF for communication and NHibernate for persistence purposes. Actually, the solution can be configured to use one of the following persistence implementations: NHibernate, EF, InMemory and RavenDB.

Designing enterprise applications requires a comprehensive set of skills. In small
and medium projects allocation of time and resources could be not feasible to the
extent that is in larger projects, it is at this time where a source for best practices
and patterns can become very beneficial. There are plenty articles, books and other
materials covering specific aspects but it is almost impossible to find a single
place where all the technologies and patterns are used in conjunction providing
a comprehensive discussion of the why and how.

The intention of these articles is to provide an example of how a full enterprise
application is developed from the early stages to a full functional stage. The articles
build on top of each other where new aspects are covered or/and existing functionality
is enhanced as a result of aligning the architect to the business non-functional
requirements.

It is assumed in the series that Agile practices are followed so the solution's
architect focuses in providing flexible mechanisms for RAD, DDD and TDD methodologies.
One key aspect of the architect is the requirement to be able to deploy a full-functional
client for business exploration purposes that requires a minimum infrastructure
footprint; avoiding databases, deployment to IIS and so on.

Background

The architect requirements are as follow:

Rich client using WPF

Client connects to server using WCF services

NHibernate, EF, RabenDB are used for persistence purposes

Client application can be run against in-memory repositories (Exploration Client)

Deployment of the exploration client must be kept simple

The application must be easily testable, tests can be run against any of the implemented repositories

Other assumptions:

We have full control over the client and server components

We are creating the database from scratch, we are not using some legacy database

We are deploying the server components using IIS7 and WAS; we will use TCP/IP

We have full design control over the PK in the database tables, we will using unique
long fields for all our entities in this project

The eDirectory solution

We are going to start using a very simple business scenario in our series, the focus
on the series is the architecture not the business domain. We may extend our domain
in the future if we find that we want to explore some more complex architect concepts.

The business domain is based in a simple list of contacts, it is currently
so simple that one single entity is only required: Customer. The solution name is
eDirectory.

The latest version can be found at the trunk branch, each chapter is located at
its own tag branch. You may want to use the browse function within Codeplex to navigate
among the branches.

Architect Overview

The eDirectory application defines three well differentiated application components:
the database, server and client.

Within the client and server the application is structured into layers, in most
cases the layers are stacked one beside each other, continuous layers are provided
with decoupled mechanisms so different implementations can be used. Some services
are available across multiple layers.

As we earlier mentioned, we have full control of the clients and server. So we will
not relay on late service discovery, instead the service contracts are available
at both sides of the application. This is also true for the DTOs and some common
business validation. As a result, a Common assembly is defined that contains components
shared by the server and client applications.

In the server side we find the core components, the business domain declares the
business entities and their behavior (action methods). Then services are declared
that exposes our domain action methods. The services for persistence and
serialisation constraints only expose DTOs between the client and server. As a result,
the transformation of entities to DTOs needs to be addressed in a comprehensive
manner.

In order to decouple our business domain from the database, the repository
components are responsible for the persistence of our entities. We will define a
generic interface between these two layers. Four concrete implementations of the
repositories are available: in-memory, NHibernate, Entity Framework and RavenDB.

The transaction manager is our "unit of work" implementation. It is responsible
for our business transactions and the handling of business messages (warnings and
exceptions).

Finally, but not the least, we have the client components. The client is a WPF application
designed using the MVVM pattern. This pattern provides a neat view XAML component
with none or very little code behind, the binding capabilities of XAML in conjunction
with the ViewModel class leverages how the client renders the DTOs provided by the
services layers.

The client decouples the service layers into two main components. The adapter is
responsible for the managing of business messages retrieved during the execution
of services. The WCF Proxy layer is responsible for the management of WCF services,
the design is neat and is a nice way of decoupling the client from the WCF service.

Future chapters

Chapter

State

Azure Deployment - In-memory WebRole

Source code is available

History

14 June 2010 - Introduction article was created.
28 June 2010 - Chapter I is done and series are published.
05 July 2010 - Chapter II was added to the series
10 July 2010 - Chapter III was added to the series
16 July 2010 - Chapter IV was added to the series
23 July 2010 - Chapter V was added to the series
31 August 2010 - Chapter VI was added to the series
04 September 2010 - Chapter VII was added to the series
15 September 2010 - Chapter VIII was added to the series
19 September 2010 - Chapter IX was added to the series
07 October 2010 - Source code for Chapter XII is available at CodePlex
16 October 2010 - Chapter X was added to the series
04 November 2010 - Chapter XI was added to the series
24 November 2010 - Chapter XII was added to the series
12 December 2010 - In-memory WebRole is deployed to MS Azure
19 December 2010 - Chapter XIII was added to the series
07 January 2011 - Chapter XIV was added to the series
09 February 2011 - Chapter XIV section 2 was added to the series
07 October 2011 - Client re-factor was made available on Codeplex
20 October 2012 - SQL-CE 4.0 support was added to the solution
16 December 2012 - RavenDB implementation
12 February 2013 - Entity Framework implementation28 May 2013 - Mention to the LiteDispatch MVC project in Azure

Comments and Discussions

First of all, I'm really enjoying reading your articles. So far I’m at the middle, but can't wait to ask question.

Our project is Winforms+NHibernate application, no client-server communications. All users remote to the same machine and run application from there. Each field has its own server (machine). I’m trying to see pros and cons of client-server approach (assuming that client and server are installed on the same system) against just having single application. So far I could say:
Pros: more scalable solution, potentially allows client-server separation (having clients access server from outside).
Cons: more complicated architecture, worse performances (overheads due transferring/serialization objects)
Please let me know if you would consider client-server approach if they both installed on the same machine.

In case if it will be just application (not client-server). Do you think that your solution can be easily adopted for non client-server case?

Please let me know if you would consider client-server approach if they both installed on the same machine

Your configuration is the simplest in terms of components and deployment; and for a limited number of users is probably adequate in terms of memory/processor/database connections. Now, you should use a conservative approach when it comes to caching in NHibernate; with the configuration you describe, you should only use cache for read-only entities.
As you say, it all depends on the number of users and server resources.

Denis Kozlov wrote:

In case if it will be just application (not client-server). Do you think that your solution can be easily adopted for non client-server case?

Yes, the series is just about this aspect. The point is to realise how to use DI and the interface contracts so we can easily provide different infrastructures but without changing our user interface and business logic. In the series, we only bring WCF in chapter XII, before that we execute both the user interface, business logic/domain and nhibernate in one single process.
I hope the series is making clear the point that WCF is a pluggable component, as the database component is.

I am going to start a new project where we only require an standalone in-process application like yours, I dont like to over-engineering but I hope I can apply the series infrastructure model ensuring the application can be deployed client-server if required.

- I got asp.net 4.0 web site, with one "FooService.svc" that inherits some service class (compiled in different project).
- I'm using windows forms as a client to talk to my FooService.svc
- All works well until the client starts getting "Cant activate service" exception
- If i browse my FooService.svc with IE i get something like:

What i think is happening (no clue):
- asp.net/app pool for some reason inits recompile/recycle of .svc?!
- the compiler for some reason fails to make "App_Web_yn1v0b1k.dll" (in the case i posted up)
- asp.net tries to use/reference the non-existing dll - then responses exception

To fix the problem i either have to restart iis, or make change in web.config to init re-compile again.

I googled a lot and found other users with same trouble, but no solutions that worked.

I saw this sort of issues years ago with IIS 6 and W2003 when a new version was deployed to the servers for a classic SOAP Web Services application. They issue was always related to the temporally files that IIS generates, we had to ensure that the old temp assemblies were removed from that location when this issue was taking place. The major difference to your issue is that we had the problem straight after the application was deployed and not at later stage, I am not sure, are you saying that you are deploying the solution and the FooService service runs for a while before it throws the mentioned exception?

I wonder how you are deploying the application to the server and also if the problem re-occurs once you re-start IIS or force an application re-start touching the web config.

And yes, it never fails after deployment. It only happens after some time and re-deployment actually fixes the service if it was down.

On one site, we had to implement a timer that calls "echo" method on service in intervals, and if it doesn't reply, it appends a space on end of web.config to init re-compile and fix the service. (i know its nasty, but we're cant find any other quick fix / or the source of problem)

The websites are not precompiled (altho they have some functionality in external dlls) / they are classic web sites (with app_code). Deployment is still all manual (copy/paste over mstsc).

We also tryed to move the service code from app_code into its own dll; .svc just inheriting that class (thinking if its compiled, iis wont recompile it) but we get same error after some time.

The biggest problem is, we cant simulate the error and sometimes it works for days before the exception starts raising.

Right now, we're thinking of changing the services to self-hosting services (to get IIS out of the compile process) with MS port sharing service. I only started reading about this, but i'm guessing the problem will be gone this way.

At this moment i'm try to apply your great patterns from this article. Also i need to add some authorization functionality to client application. Let's we have a user name and passward and let's server API needs this data at every request (over https). I see some ways to modify your patterns for this purposes. For example, is it suitable to add a new methods getCustomerService(username, password) to IContractLocator interface (or set auth data to it's concrete implementations through properties)? Another way is to set authorization data to global context of client application (only one user can use application).
Enrique, what you can advice me about this problem?

From my experience, application security is based on setting visibility on menus, buttons and so for.
I normally map AD principals to application roles that contain application permissions. In a recent WPF project, we enabled a server method that returned a list of application permissions available for the user. (ServiceSecurityContext is used on WCF to gather the current WindowsIdentity details). Then, in the client side, we developed extended controls from standard controls with DependencyProperties that can be used in the XAML to indicate which application permission is required to enable/display the control.

You may also want to add an additional security/authorisation checking in the server methods. I can think of couple solutions, probably something similar to the implementation (InstanceCreationAttribute<code>) of <code>IContractBehavior but instead an implementation of IOperationBehavior may do the trick.

As you indicated the ViewModel knows about the View, line 01. And the ViewModel is responsible for the creation and initialisation of the View, line 02. The reason I keep a reference to the View is to be able to trigger some actions on the View in my commands. Simple things like closing the window and so for:

I could have a more generic reference, instead of declaring a reference to CustomerDetailView, instead it could be a reference to Window or even better to some interface that encapsulates the required functionality. I should also add some additonal code/logic to ease the testing of the ViewModel without creating a instance of a Window.